繁体   English   中英

来自childNodes的appendChild不起作用

[英]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);
}

选项

  1. to.appendChild()需要HTML,但是from.childNodes [i]是节点对象,因此所有框都将包含文本[Object Node]。
  2. document.createElement()重用具有相同标签的现有元素,因此仅将一个框添加到文档中。
  3. 同一个链接元素不能有多个父元素,因此只有一个框最终带有链接。
  4. 必须使用setAttribute()设置链接的href。 设置属性link.href不会执行任何操作,因此框中的任何链接都不会指向任何地方。

我猜答案是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); } 

另请参见appendChild仅在第一次工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM