doubleyong
管理员
管理员
  • 最后登录2025-12-02
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:7139回复:1

js中关于document.write的剖析

楼主#
更多 发布于:2020-03-11 09:51
document.write() 其它并不那么简单。下面我们就来了解一下它。

Document.write() 法将一个文本字符串写入一个由 document.open() 打开的文档流(document stream)。
注:document.write写入的是由document.open打开的文档流。
因为 document.write 需要向文档流中写入内容,所以,若在一个已关闭(例如,已完成加载)的文档上调用 document.write就会自动调用 document.open,这将清空该文档的内容。


大家,注意上面这句话:"若在一个已关闭的文档上调用 document.write就会自动调用 document.open,这将清空该文档的内容". 这句话,解释了,我们在某些时候使用document.write()写入数据时,会将原来的内容清空。

示例说明:
1. 如果 document.write() 调用发生在 HTML 里的 <script> 标签中,那么它将不会自动调用 document.open()则不会清空原来的内容


详见如下例子:
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
    &lt;script type="text/javascript"&gt;
       document.write("hello world");
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
   &lt;p&gt;这是一个段落&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
script标签写在html下面,效果一样,不会清空原来的内容

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
   &lt;p&gt;这是一个段落&lt;/p&gt;
  &lt;script type="text/javascript"&gt;
       document.write("hello world");
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


2. 向一个已经加载,并且没有调用过
document.open() 的文档写入数据时,会自动调用 document.open会发现原来的内容会被清空

代码如下:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
    &lt;script type="text/javascript"&gt;
      function test(){
          document.write("hello write");
      }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body onload="test()"&gt;
   &lt;p&gt;这是一个段落&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;


还有:
一旦完成了数据写入,建议调用 document.close(),以告诉浏览器当前页面已经加载完毕。写入的数据会被解析到文档结构模型(DOM)里。


代码如下:

function test(){
         document.open();
         document.write("hello write");
         document.close();
     }

注意:document.write 和 document.writeln 在 XHTML 文档中不可用(控制台上会显示 "Operation is not supported"[NS_ERROR_DOM_NOT_SUPPORTED_ERR] 的报错信息)。 当打开本地的 .xhtml 格式的文件或任何其他 MIME 类型为 application/xhtml+xml 的文档时,均会报错。更多信息可查看 W3C XHTML FAQ

注意:在有deferredasynchronous 属性的 script 中,document.write 会被忽略,控制台会显示 "A call to document.write() from an asynchronously-loaded external script was ignored" 的报错信息。


注意:在 Edge 中,在 <iframe> 内部调用 document.write 多于一次时会引发错误 SCRIPT70: Permission denied。


注意:从 Chrome 55 开始,Chrome(可能)不会运行通过 document.write() 注入的<script>,以防止使用 2G 连接的用户找不到 HTTP 缓存。前往此链接查看这种情况发生需要满足的条件。


参考官方文档:
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/write

最新喜欢:

小达人小达人 丶红丝错千重丶红丝错千重
知识需要管理,知识需要分享
tieren
贫民
贫民
  • 最后登录2020-04-03
  • 发帖数1
沙发#
发布于:2020-03-29 16:40
有多少人回复
游客


返回顶部

公众号

公众号