简体   繁体   中英

How do I remove all events of a type from an element

I want to remove ALL click events from a certain DOM element. How? There is removeEventListener , but that requires the attached function.

Is there a way to remove ALL attached events of one type (or just ALL, that's fine too)?

This article would probably be useful:

http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/

One part in particular is a recursive function that removes all click events. Remember that jQuery will remove click events IF the click event was created using jQuery. the function given in the article will remove both those created with jQuery and those that were not. The function given is this:

function RecursiveUnbind($jElement) {
    // remove this element's and all of its children's click events
    $jElement.unbind();
    $jElement.removeAttr('onclick');
    $jElement.children().each(function () {
        RecursiveUnbind($(this));
    });
}

You would call the function like this:

RecursiveUnbind($('#container'));

That function takes a jQuery object parameter, but you could easily change it up to pass a string as the name of the ID for the element, or however you think is best.

Unfortunately, there is no method in the DOM specification that can list or remove event listeners without already knowing the listener function.

The best you can do is to create a new element of the same type, copy all properties and move children from the original element to the new one.

You didn't mention whether or not you were using a library to assist in DOM manipulation, but if you're using jQuery, its as simple as $(domelement).unbind('click'); Documented here: http://api.jquery.com/unbind/

如果要删除所有事件侦听器,如何为 onclick 事件分配一个空函数?

<YOUR_HTML_ELEMENT>.onclick=function(){};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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