【问题标题】:Clone element with all its events克隆元素及其所有事件
【发布时间】:2013-06-05 11:57:22
【问题描述】:

我正在克隆页面中的文本区域,但克隆的元素没有主元素的任何事件,有没有办法克隆克隆元素中的所有事件?

var dupNode = node.cloneNode(deep);

【问题讨论】:

标签: javascript dom-events clonenode


【解决方案1】:

您可以在节点上使用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);

但似乎 getEventListeners 并不受支持:

Get event listeners attached to node using addEventListener


如果您还需要复制节点上的所有事件属性,则需要一个所有事件的列表,然后简单地复制它们:

['onclick', 'onmouseover', '...'].forEach(function(method) {
    dupNode[method] = node[method];
});

【讨论】:

    【解决方案2】:

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

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

    不用addEventListener,只需创建函数FunctionName。好吧,如果您要扩展使用 addEventListener 的对象,这是没有用的

    【讨论】:

    • 这如何回答 OP 的问题? startRecorind 是什么?什么是typ
    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多