我正在尝试使用此代码克隆 javascript div id
<script>
var div = document.getElementById('pruebaz2'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "pruebaz2";
document.body.appendChild(clone);
</script>
但我的克隆 div id 对我的 html 页面没有任何影响
我的原始id在点击时添加了一条记录
我的克隆 ID 什么都不做
我如何克隆具有相同功能的
您的代码没问题。你只是没有将任何内容放入克隆的 div 中,所以没有什么可看的。
另外,不要给两个元素相同的 id。这违背了它的目的。
最后,“深度”克隆不会复制事件处理程序。来自 MDN :
Cloning a node copies all of its attributes and their values,
including intrinsic (in–line) listeners. It does not copy event
listeners added using addEventListener() or those assigned to element
properties. (e.g. node.onclick = fn) Moreover, for a element,
the painted image is not copied.
var div = document.getElementById('pruebaz2'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "pruebaz3";
clone.innerHTML = "Cloned DIV";
document.body.appendChild(clone);
<div id="pruebaz2">Original DIV</div>