一种解决方案是为 addEventListener 编写自己的包装器,该包装器会记住已添加的侦听器,因此可以“重放”它们:
// set an event handler after memoizing it
function myAddEventListener(element, type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!element.listeners) { element.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
element.listeners[element.listeners.length] =
Array.prototype.slice.call(arguments,1);
// apply listener to element itself
element.addEventListener (type, listener, useCapture);
}
// copy a list of event handlers from one element to another
function copyEventListeners (from_element, to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<from_element.listeners.length; i++) {
Element.addEventListener.apply (to_element, from_element.listeners[i]);
}
}
}
然后:
function clone_with_listeners (element) {
var cloned_element = element.cloneNode();
copyEventListeners (element, cloned_element);
return cloned_element;
}
如果您没有宗教信仰阻止您覆盖 Element 对象上的原始方法:
var orgAddEventListener = Element.addEventListener;
// our version of addEventListener
Element.addEventListener = function (type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!this.listeners) { this.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
this.listeners[element.listeners.length] =
Array.prototype.slice.call (arguments,0);
// apply listener to element itself
orgAddEventListener.call (element, type, listener, useCapture);
};
// copy a list of event handlers from this element to another
Element.copyEventListeners = function (to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<this.listeners.length; i++) {
Element.addEventListener.apply (to_element, this.listeners[i]);
}
}
};
接着:
Element.cloneNode = function () {
var cloned_element = this.cloneNode();
this.copyEventListeners (cloned_element);
return cloned_element;
};