克隆元素及其所有事件 [英] Clone element with all its events
本文介绍了克隆元素及其所有事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在页面中克隆了一个textarea,但是克隆元素没有任何主要元素的事件,有没有办法克隆克隆元素中的所有事件?
I'm cloning a textarea in a page but the cloned element doesn't have any event of the primary element, is there any way to clone all events in cloned element?
var dupNode = node.cloneNode(deep);
推荐答案
你可以使用 getEventListeners
在节点上?不知道支持是怎么回事,或者它是否只在控制台中支持?
You can maybe use getEventListeners
on nodes? Don't know how the support is, or if it's only supported in the console?
function cloneMassive(node) {
// Clone the node, don't clone the childNodes right now...
var dupNode = node.cloneNode(false);
var events = getEventListeners(node);
for(var p in events) {
// All events is in an array so iterate that array:
events[p].forEach(function(ev) {
// {listener: Function, useCapture: Boolean}
dupNode.addEventListener(p, ev.listener, ev.useCapture);
});
}
// Also do the same to all childNodes and append them.
if (node.childNodes.length) {
[].slice.call(node.childNodes).forEach(function(node) {
dupNode.appendChild(cloneMassive(node));
});
}
return dupNode;
}
var dupBody = cloneMassive(document.body);
但似乎 getEventListeners
不是真的支持:
使用addEventListener获取附加到节点的事件侦听器
如果需要复制所有事件属性节点,你需要一个所有的列表,然后简单地复制它们:
If you need to copy all event properties on the node as well you will need a list of all, and then simply copy them over:
['onclick', 'onmouseover', '...'].forEach(function(method) {
dupNode[method] = node[method];
});
这篇关于克隆元素及其所有事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文