javascript - 是否可以在 javascript 中克隆具有相同功能的 javascript div id?

标签 javascript jquery css

<分区>

我正在尝试使用此代码克隆 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>

关于javascript - 是否可以在 javascript 中克隆具有相同功能的 javascript div id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979475/

相关文章:

javascript - 显示 div 何时获得选择或选项

ios - 仅在 iPhone 上的 Safari 上出现突然的 CSS 样式问题

CSS 旋转和 IE : absolute positioning seems to break IE

html - 折叠框(图像菜单)

javascript - 使用对象的 for 循环打印出每个唯一对象的属性

javascript - 在表单提交js上重新格式化引导日期选择器

javascript - 使用 NicEdit 调整图像大小

javascript - 哪些选项可以使用 Google Cloud Vision 改进 OCR?

javascript - 如果 js 确认返回 false,则重置回选择字段上的上一个选项

jquery - 扩大圆圈导致移动屏幕调整大小