如何使用事件侦听器复制 DOM 节点? [英] How to copy a DOM node with event listeners?
本文介绍了如何使用事件侦听器复制 DOM 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过了
node.cloneNode(true); // deep copy
它似乎没有复制我使用 node.addEventListener("click", someFunc);
添加的事件侦听器.
It doesn't seem to copy the event listeners that I added using node.addEventListener("click", someFunc);
.
我们使用 Dojo 库.
We use the Dojo library.
推荐答案
cloneNode()
不复制事件侦听器.事实上,一旦事件侦听器被附加,就无法通过 DOM 获取它们,因此您的选择是:
cloneNode()
does not copy event listeners. In fact, there's no way of getting hold of event listeners via the DOM once they've been attached, so your options are:
- 手动将所有事件侦听器添加到您的克隆节点
- 重构您的代码以使用事件委托,以便所有事件处理程序都附加到包含原始和克隆的节点
- 使用围绕
Node.addEventListener()
的包装函数来跟踪添加到每个节点的侦听器.这就是 jQuery 的clone()
方法能够复制节点及其事件侦听器的方式,例如示例.
- Add all the event listeners manually to your cloned node
- Refactor your code to use event delegation so that all event handlers are attached to a node that contains both the original and the clone
- Use a wrapper function around
Node.addEventListener()
to keep track of listeners added to each node. This is how jQuery'sclone()
method is able to copy a node with its event listeners, for example.
这篇关于如何使用事件侦听器复制 DOM 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文