[英]appendChild from childNodes doesn't work
我在网上看到了一个有趣的问题,但不知道答案:
以下代码旨在添加五个完全相同的框,其中包含指向文档的链接,但无法正常工作。 为什么不?
// 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);
}
选项 :
我猜答案是3,但不确定,也不知道为什么?
有什么解释吗? 特纳克斯
您只应从i = 0迭代到copyContent
childNodes.length-1。 另外,如果要将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); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.