document.write(markup)是一个比较常用的语句,不过对它的规定其实没真正看过,直到看到有人问在才令我想起去看看语言定义。

在MDN上找到。

向由打开的文档流写入字符串。

示例代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<html>

<head>

<title>write example
</title>

</head>


<bodyonload="newContent();">


<h1>Origin
</h1>


<scripttype="text/javascript">


       document.write("document.write"); // 第一次write


       function newContent(){

           alert("load new content");

           document.open();

           document.write("
<h1>Out with the old - in with the new!
</h1>");

           document.close();

       }

</script>


<p>Some original document content.
</p>

</body>

</html>

运行上面代码,将会看到页面输出Origin的内容,同时弹出对话框;当点击确定后页面内容将变为新的h1的内容,而原来的内容消失。

可以看到的是,第一次document.write的内容是直接附加到文档流中,而第二次则是冲掉了原来的文档流。这里很关键的一个就是document.open()这语句。

参照MDN说明,document.open()将会打开一个文档流来输入内容,当文档已存在的时候,则先清空。并且,当页面已经加载完成时调用document.writedocument.open会自动先运行,而写入结束后,document.close也将自动运行。

故上面的代码中,第二次write是绑定在load事件,文档已加载完,document.open将会清空原文档内容然后写入新内容。事实上,这种情况下不用显式调用document.opendocument.close

根据以上内容,在jQuery中使用document.write会出现问题的原因就不言而喻了。因为在使用jQuery的时候,一般我们都是在$(document).ready()中写相关代码,而这时文档结构已完成,使用document.write将会清空文档。如果使用jQuery的时候需要附加写入内容,使用append方法会更好。

最后,还是那句话,每一门实用的语言都是博大精深的。