document.write()做什么? [英] What does document.write() do?

查看:237
本文介绍了document.write()做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题。
我有这个脚本:

This is a very basic question. I have this script:

    <script type="text/javascript">
        function write(){
            document.write('Hello2')
        }
        write();
    </script>

它显示我的完整页面。在页面末尾将显示 Hello2
但是当我去开发工具并调用 write()时,它将替换我的整个身体html。只是好奇才知道。

It shows my complete page. And at the end of page Hello2 will be displayed. But when ever I go to developer tools and call write(), it will replace my entire body html. Just curious to know.

        window.onload=write;// has the same effect. Clear's my page.

谢谢。

推荐答案

当浏览器读取并解析文档时,如果有一个脚本元素,则调用 document.write ,此时将 document.write 的输出插入到文档中。但是,稍后,一旦页面完全加载,如果你使用 document.write ,它会隐式执行 document.open ,它擦除页面并开始从头开始编写新文件。

When the document is being read and parsed by the browser, if there's a script element that calls document.write, the output of document.write is inserted into the document at that point. Later, though, once the page is fully loaded, if you use document.write, it implicitly performs a document.open, which wipes out the page and starts writing a new one from scratch.

关于MDN的更多信息:

More on MDN:

  • document.write
  • document.open

一般来说,而不是使用 document.write 将内容添加到页面,使用各种 DOM方法(直接或通过像 jQuery 这样的库, YUI 关闭,或其他几个人)。

In general, rather than using document.write to add content to a page, use the various DOM methods (either directly, or via a library like jQuery, YUI, Closure, or any of several others).

这篇关于document.write()做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆