这是我在网上看到的一个有趣的问题,但我不知道答案:
以下代码旨在添加五个包含文档链接的相同框,但它无法正常工作。为什么不呢?
// 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,但不确定,也不知道为什么?
任何解释? TNX
答案 0 :(得分:3)
您应该只在copyContent
中从i = 0迭代到childNodes.length - 1。此外,如果要将它们附加到文档中的多个位置(=第3个选项),则应该clone 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);
}