document.write内部for循环 [英] document.write inside for loops
问题描述
我有以下HTML文档
<html>
<script>
function explode() {
pp = document.getElementsByTagName("a");
for(i=0;i<pp.length;i++) {
document.write(pp[i].href);
}
}
</script>
<body>
<a href="http://google.com">Google</a>
<a href="http://yahoo.com">Yahoo</a>
<button onclick="explode()">Explode</button>
<body>
</html>
执行后,我希望所有超链接都打印在我的窗口上,但只有第一个。有人可以解释一下吗?
When executed I expect all the hyperlinks printed on my window, but I get only the first one. Can someone explain this
更新
我相信 document.write
将重置页面内容,但是如果是这样,那么我已经在变量 pp
中创建了对象列表,并且在for循环结束时应该获得LAST元素,为什么要获得第一个元素?
Update
I am convinced by the answer that document.write
will reset the page contents, but if it is that so then, I already the list of objects in the variable pp
and by the end of the for loop I should get the LAST element, why the first element ?
推荐答案
如果在完全加载文档后开始写文档,您将隐式打开一个新文档并替换当前文档。您可以使用 document.write
在文档加载时将其添加到文档中(即,在代码中内联的脚本标签中),但是一旦文档完成,请使用 document.write
将隐式调用 document.open
来创建要写入的新文档。
If you start writing to the document after it has been completely loaded, you will implicitly open a new document and replace the current document. You can use document.write
to add to the document while it is loading (i.e. in scripts tags inline in the code), but once the document is complete, using document.write
will implicitly call document.open
to create a new document to write to.
您从获得的元素列表 getElementByTagName
方法返回活动列表,当元素添加到DOM或从DOM中删除时,该列表会更新。将第一项写入文档后,该列表为空,因为文档中不再有任何匹配的元素。
The list of elements that you get from the getElementByTagName
method returns a live list, which is updated when elements are added to or removed from the DOM. When you have written the first item to the document the list is empty, as there aren't any matching elements in the document any more.
这篇关于document.write内部for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!