无法将同一个孩子追加到由javascript创建的两个div元素 [英] not able to append same child to two div elements created by by javascript

查看:77
本文介绍了无法将同一个孩子追加到由javascript创建的两个div元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  while(i< check){
randImage = retImgNodes(); //返回图像节点
div1.appendChild(randImage); //追加到div1
console.log(added div1);
randImage2 = randImage; //变量名不是问题
div2.appendChild(randImage2);
console.log(attached div2);
i ++;
// txt = document.createTextNode(hi)
//div2.appendChild(txt);
}
theBody.appendChild(div1);
theBody.appendChild(div2);


解决方案

通过设计,您无法将单个元素位于DOM中的多个位置。如果您尝试这样做,元素将从当前位置移动到您插入它的位置。



如果您愿意,可以创建一个副本通过使用 cloneNode() code> 。然后,您可以将该副本插入到不同位置的DOM中。



您可能需要阅读 documents nodes 元素



例如 appendChild()在MDN上表示(重点是我的):


Node.appendChild()方法将节点添加到指定父节点的子项列表的末尾。 如果给定的孩子是对文档中现有节点的引用,则appendChild()将其从当前位置移动到新位置(不需要在添加之前从其父节点中删除该节点它到了其他节点)。

这意味着一个节点不能同时在文档的两个点上。所以如果节点已经有父节点,节点首先被删除,然后附加到新的位置。 Node.cloneNode()可以用于复制节点,然后将其附加到新的父节点下。请注意,使用cloneNode创建的副本不会自动保持同步。



while(i < check){
    randImage = retImgNodes();  //return image nodes
    div1.appendChild(randImage);  //append to div1
    console.log("appended div1");
    randImage2 = randImage;       //variable name is not a problem
    div2.appendChild(randImage2);
    console.log("appended div2");
    i++ ;
    //txt = document.createTextNode("hi")
    //div2.appendChild(txt);
}
theBody.appendChild(div1);
theBody.appendChild(div2);

解决方案

By design, you are not able to place a single element in more than one location in the DOM. If you attempt to do so, the element will be moved from its current location to the location where you are inserting it.

If you desire, you can create a duplicate of a node by using cloneNode(). You can then insert that duplicate into the DOM at a different location.

You might want to read the documentation for documents, nodes, and elements.

For instance the documentation for appendChild() on MDN says (emphasis mine):

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.

这篇关于无法将同一个孩子追加到由javascript创建的两个div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆