[英]appendChild from childNodes doesn't work
This is an interesting question I saw on the net but didn't know the answer: 我在网上看到了一个有趣的问题,但不知道答案:
The following code is intended to add five identical boxes containing links to the document, but it doesn't work properly. 以下代码旨在添加五个完全相同的框,其中包含指向文档的链接,但无法正常工作。 Why not?
为什么不?
// Copies the contents of one box into another
function copyContents(from, to){
for( var i=0; i<=from.childNodes.length-1; i++){
to.appendChild(from.childNodes[i]); // <---- Error on this line.
}
}
//create a box to copy:
var referenceBox = document.createElement('div');
var link = document.createElement('a');
link.href = 'http://www.example.com/';
link.textContent = 'A link';
referenceBox.appendChild(link);
//Add box copies to the document
for(var i=0; i<5; i++){
var newBox = document.createElement('div');
copyContents(referenceBox, newBox);
document.body.appendChild(newBox);
}
Options : 选项 :
I guess the answer is 3, but not sure and don't know why? 我猜答案是3,但不确定,也不知道为什么?
Any explanation? 有什么解释吗? Tnx
特纳克斯
You should only iterate from i = 0 to childNodes.length - 1 in copyContent
. 您只应从i = 0迭代到
copyContent
childNodes.length-1。 Also, you should clone DOM nodes if you want to append them to multiple locations in your document (= 3rd option): 另外,如果要将DOM节点附加到文档中的多个位置,则应克隆 DOM节点(=第三个选项):
// Copies the contents of one box into another: function copyContents(from, to) { for (var i = 0; i < from.childNodes.length; i++) { // <-- change <= to < to.appendChild(from.childNodes[i].cloneNode(true)); // <-- add cloneNode(true); to clone node and all its children } } // Create a box to copy: var referenceBox = document.createElement('div'); var link = document.createElement('a'); link.href = 'http://www.example.com/'; link.textContent = 'A link'; referenceBox.appendChild(link); // Add box copies to the document: for (var i = 0; i < 5; i++) { var newBox = document.createElement('div'); copyContents(referenceBox, newBox); document.body.appendChild(newBox); }
See also appendChild only works first time 另请参见appendChild仅在第一次工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.