简体   繁体   English

如何在不删除原件的情况下复制元素?

[英]How copying elements without deleting originals?

I have a loop to duplicate an array, and another to add copy in another div.我有一个循环来复制一个数组,另一个循环在另一个 div 中添加副本。 Both loop work good but original element are deleted, someone can explain me why?两个循环都运行良好但原始元素被删除,有人可以解释我为什么吗? And how can i fixe it?我该如何解决? Thank you!谢谢!

 var mesElements = document.querySelectorAll('.element'); var catchCopy = document.querySelector('.parent_copy'); var mesElementsCopie = [] for(var j = 0; j < mesElements.length; ++j){ mesElementsCopie[j] = mesElements[j]; } for(var k = 0; k < mesElements.length; ++k){ catchCopy.appendChild(mesElementsCopie[k]); }
 <div class="parent_element" style="background-color: red;"> <div class="element">text</div> <div class="element">text</div> <div class="element">text</div> </div> <div class="parent_copy" style="background-color: green;"></div>

On this line, you do not copy the node, but rather you create two references to the same DOM node:在这一行,您不复制节点,而是创建对同一个 DOM 节点的两个引用:

mesElementsCopie[j] = mesElements[j];

You should use thecloneNode() method:您应该使用cloneNode()方法:

mesElementsCopie[j] = mesElements[j].cloneNode(true);

Here's the fixed code:这是固定代码:

 var mesElements = document.querySelectorAll('.element'); var catchCopy = document.querySelector('.parent_copy'); var mesElementsCopie = [] for(var j = 0; j < mesElements.length; ++j){ mesElementsCopie[j] = mesElements[j].cloneNode(true); } for(var k = 0; k < mesElements.length; ++k){ catchCopy.appendChild(mesElementsCopie[k]); }
 <div class="parent_element" style="background-color: red;"> <div class="element">text</div> <div class="element">text</div> <div class="element">text</div> </div> <div class="parent_copy" style="background-color: green;"></div>

You were adding the same elements you had grabbed from the parent element, so it was just moving them to the parent copy.您正在添加从父元素中获取的相同元素,因此它只是将它们移动到父副本。 Use .cloneNode(true) to make sure you're not using the same element.使用.cloneNode(true)确保您没有使用相同的元素。

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

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