Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

使用document.write输出时会清空当前文档流的问题

<body>
    <ul>
        <li>5</li>
        <li>4</li>
    </ul>
    <button type="button" onclick="ff()">ff</button>
    <script type="text/javascript">
        var li = document.getElementsByTagName('li');
        function ff(){
            for(var i = 0; i < li.length;i++){
                document.write(li[i].innerHTML);
            }
        }    
    </script>
</body>

最后页面上只会输出5,我设置断点看了以后发现,经过第一次循环,li的长度会变成0,所以就退出循环了,有人说使用document.write输出时会清空当前文档流,但是清空的话又怎么会输出5呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

情况一:直接写

  document.write('不会覆盖当前文档流');

此时document.write直接在当前文档流最后写入

情况二:文档加载完毕后写入

  window.onload=function(){
  document.write('当前文档流会被覆盖');
  };

1、onload为文档加载完毕后,此时文档流已关闭
2、再使用document.write则会先执行document.open()创建一个新文档流
3、这个新文档流将会覆盖替换掉之前的文档流

你用onclick事件也是同上的情况


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...