首页 > web前端 > js教程 > 正文

为什么 document.write() 会清除页面?

Susan Sarandon
发布: 2024-10-24 06:59:30
原创
751 人浏览过

Why Does document.write() Clear the Page?

为什么 Document.write 会清空页面?

在 JavaScript 中使用 document.write() 方法时,程序员经常会遇到一个奇特的情况行为:在事件处理程序(例如 onClick)中调用 document.write() 可能会导致文档被清除。

要理解这种意外结果,必须掌握 document.write() 的本质。此函数写入文档流,文档流是表示浏览器中显示的文档的连续数据流。

在提供的代码示例中:

<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>
登录后复制

validator() 函数单击“验证”按钮时触发。发生的情况如下:

  1. 此时,文档可能已完成加载,这意味着文档流已关闭。
  2. 调用 document.write() 自动触发 document.open( ),这会清除当前文档,删除所有现有元素。
  3. 随后,在 document.write() 中指定的文本将呈现在现在为空的文档中。

因此,表单元素(复选框和按钮)从页面中删除,因为整个文档被刷新,用 document.write() 的输出替换以前的内容。

因此,在使用 document.write() 时,在写入文档流之前显式使用 document.open() 确保文档流保持打开状态至关重要。否则,清除文档的不可预测的行为可能会破坏预期的功能。

以上是为什么 document.write() 会清除页面?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!