Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - Clone element with all its events

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

But it seems that getEventListeners isn't really supported:

Get event listeners attached to node using 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];
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...