Why Does Document.write Clear the Page?
When using the document.write() method in JavaScript, programmers often encounter a peculiar behavior: invoking document.write() within an event handler, such as onClick, may result in the document being cleared.
To understand this unexpected outcome, it's essential to grasp the nature of document.write(). This function writes to the document stream, which is the continuous flow of data representing the document being displayed in the browser.
In the provided code example:
<code class="html"><form name="myForm"> <input type="checkbox" name="thebox" /> <input type="button" onClick="validator()" name="validation" value="Press me for validation" /> </form> <script type="text/javascript"> function validator() { if (document.myForm.thebox.checked) { document.write("checkBox is checked"); } else { document.write("checkBox is NOT checked"); } } </script></code>
The validator() function is triggered when the "validation" button is clicked. Here's what happens:
Consequently, the form elements (checkbox and button) are removed from the page because the entire document is refreshed, replacing the previous contents with the output of document.write().
Therefore, when working with document.write(), it's crucial to ensure that the document stream remains open by using document.open() explicitly before writing to it. Otherwise, the unpredictable behavior of clearing the document can disrupt intended functionality.
The above is the detailed content of Why Does document.write() Clear the Page?. For more information, please follow other related articles on the PHP Chinese website!