简体   繁体   English

如何使用元素的innerHTML复制元素的事件?

[英]How do I copy an element's events with its innerHTML?

I incorporated a simple lightbox functionality into my webapp: 我将一个简单的灯箱功能整合到了我的Web应用程序中:

for(var i = 0, l = figs.length; i<l; i++){
    figs[i].addEventListener("dblclick",function(){
        lightbox.style.display = "block";
        lbox.innerHTML = this.innerHTML;
    });
}

The problem is that I want the interactivity of the div to copy into the lightbox (these are graphs that each have event listeners that make them interactive). 问题是我希望将div的交互性复制到灯箱中(这些图每个都有使它们具有交互性的事件侦听器)。 Is there any way that I can accomplish this less storing all of the events inside an array and somehow copying those? 有什么办法可以减少存储所有事件并以某种方式复制这些事件呢?

Unless you are using jQuery you will not be able to clone a node with all it's event handlers and even if you could it's usually not a good idea (I could expand if you need to). 除非您使用的是jQuery否则您将无法使用其所有事件处理程序克隆节点,即使可以,通常也不是一个好主意(如果需要,我可以扩展)。

I suppose that these listeners were attached through some processes targetting these DOM nodes (eg applying a plugin). 我想这些监听器是通过针对这些DOM节点的某些过程(例如,应用插件)附加的。 What you should be doing is simply do a deep or shallow copy of the DOM elements you want using Element.prototype.cloneNode and re-execute those processes against the clones. 您应该做的只是使用Element.prototype.cloneNode您想要的DOM元素进行深层或浅层复制,然后对这些克隆重新执行这些过程。

If the cloning process is complex you might consider encapsulating it within the class which is adding the listeners. 如果克隆过程很复杂,则可以考虑将其封装在添加侦听器的中。 Something like: 就像是:

function SomeObj(el) {
    this.el = el;
    attachSomeHandlersToEl();
}

SomeObj.prototype.clone = function () {
    var newEl = this.el.cloneNode(true);

    return new this.constructor(newEl);
};

var el = document.getElementById('some-el'),
    someObj = new SomeObj(el),
    clonedEl = someObj.clone().el;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM