document.write 简介

document.write 的执行分两种情况:

第一种:dom加载已完成

1. 执行 document.open() (即会清空document)

2. 执行 document.write()

3. 执行 document.close()

看例子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  
</head>
<body>
  <p>
    This is a p tag
  </p>
  <script>
     function write() {
        document.write('nothing left')
     }
     setTimeout(write, 1000)
  </script>
</body>
</html>

一秒后整个document会清除,包括script标签,最后只留下body中的 'nothing left'

 

第二种:dom未加载完成

1. document.write() (由于js是阻塞的,页面已经在document已经在open状态,所以不会清空document)

2. document.close()

看例子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  
</head>
<body>
  <p>
    This is a p tag
  </p>
  <script>
    function write() {
        document.write('nothing left')
    }
    write()
  </script>
</body>
</html>

执行后的结果是除了那个p标签,页面的body最后又加了一个 'nothing left'

 

参考链接:http://devdocs.io/dom/document/write

posted @ 2017-04-05 21:51  savokiss  阅读(444)  评论(0编辑  收藏  举报