Remove all JavaScript event listeners of an element and its children? [duplicate]
Is it possible to remove all event listeners of an element and its children? Something like:
myElem.removeEventListeners();
I need this because I have a complex element with events, and I need to create a copy of it -- like a static image that does not react to any events.
If you use cloneNode
, the event listeners won't be copied.
If you want a robust solution your best bet is probably to write a wrapper to attach/detach
listeners, and keep track of them yourself. Something like Dean Edwards' addEvent.
I do not know of one, and a search on Google didn't yield any obvious results. One easy, kludgy solution is to create a function that cycles through every event and sets it to null
, such as
function removeEvents(obj)
{
obj.onblur = null;
obj.onchange = null;
obj.onclick = null;
// ...
}
Call this function as follows: removeEvents(myElem)
. A complete list of JavaScript event handlers can be found at http://www.elated.com/articles/events-and-event-handlers/.
Undoubtedly there is a more elegant way to write this function, but I don't know if there is a more elegant way to solve this problem. It would be lovely if someone knows of one. If you are binding events through a JavaScript library, such as jQuery, there may be other, better options.
精彩评论