简体   繁体   English

如何从元素中删除一个类型的所有事件

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

I want to remove ALL click events from a certain DOM element.我想从某个 DOM 元素中删除所有点击事件。 How?如何? There is removeEventListener , but that requires the attached function.removeEventListener ,但这需要附加功能。

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/ 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.请记住,如果单击事件是使用 jQuery 创建的,则 jQuery 将删除单击事件。 the function given in the article will remove both those created with jQuery and those that were not.文章中给出的函数将删除使用 jQuery 创建的和没有创建的。 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.该函数接受一个 jQuery 对象参数,但您可以轻松地将其更改为传递一个字符串作为元素 ID 的名称,或者您认为最好的方式。

Unfortunately, there is no method in the DOM specification that can list or remove event listeners without already knowing the listener function.不幸的是,DOM 规范中没有方法可以在不知道监听器函数的情况下列出或删除事件监听器。

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');你没有提到你是否使用库来协助 DOM 操作,但如果你使用 jQuery,它就像 $(domelement).unbind('click'); 一样简单。 Documented here: http://api.jquery.com/unbind/记录在这里: http ://api.jquery.com/unbind/

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

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

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

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