Displaying Information in the Browser (JavaScript)
To display data directly in your browser, you can use the write method of the document object. You can also display information in forms in the browser, and in alert, prompt, and confirm message boxes.
The most common way to display information is the write method of the document object. It takes one argument, a string, which it displays in the browser. The string can be either plain text or HTML.
Strings can be enclosed in either single or double quotation marks. This lets you quote something that contains quotation marks or apostrophes.
The following example illustrates use of the write method.
document.write("Pi is approximately equal to " + Math.PI); // New line. document.write("<br />"); document.write("This is an engraving of a horse."); // New line. document.write("<br />"); document.write('<img src="horse.gif">');
When you call the write method, the document is opened and cleared if it is not being opened and parsed when the write method is called. This causes potentially unexpected results. The following example shows a script that is intended to display the time every 5 seconds, but it cannot do so after the first time because it clears itself in the process.
<html> <head> <script type="text/javascript"> function ShowTime() { var dt = new Date(); document.write(dt.toTimeString()); window.setTimeout("ShowTime();", 5000); } </script> </head> <body> <script type="text/javascript"> ShowTime(); </script> </body> </html>
If you use the alert method of the window object instead of document.write, as shown in the following code, the script works.
window.alert(dt.toTimeString());
window.setTimeout("ShowTime();", 5000);
}
Tidak ada komentar:
Posting Komentar