javascript 克隆元素及其所有事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16939335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:32:19  来源:igfitidea点击:

Clone element with all its events

javascriptjavascript-eventsclonenode

提问by ehsandotnet

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?

我在页面中克隆了一个 textarea 但克隆的元素没有主元素的任何事件,有没有办法克隆克隆元素中的所有事件?

var dupNode = node.cloneNode(deep);

回答by andlrc

You can maybe use getEventListenerson nodes? Don't know how the support is, or if it's only supported in the console?

您可以getEventListeners在节点上使用吗?不知道支持如何,还是只在控制台支持?

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);

But it seems that getEventListenersisn't really supported:

但似乎getEventListeners并不真正支持:

Get event listeners attached to node using addEventListener

使用 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];
});

回答by Martin Memphis ?aniga

I was solving this problem lately and even that this is old post, just in case somebody is trying to find out, i add my solution :

我最近正在解决这个问题,即使这是旧帖子,以防万一有人试图找出答案,我添加了我的解决方案:

var button = document.createElement("i");
var click = document.createAttribute("onclick");
click.value = "FunctionName(this)";
button.attributes.setNamedItem(click);

Instead of using addEventListener, just create function FunctionName. Well this is useless if you are extending objects that use addEventListener

而不是使用addEventListener,只需创建函数FunctionName。好吧,如果您要扩展使用的对象,这将毫无用处addEventListener