javascript 元素的事件列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3910123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:39:54  来源:igfitidea点击:

List of an element's events

javascriptdom-events

提问by errorhandler

Is there a way to find all of the events for a element in javascript? or a way to unbind all events from a element?

有没有办法在javascript中找到元素的所有事件?或者从一个元素中解除所有事件的绑定?

Thanks.

谢谢。

采纳答案by Dave

There is not way to do that directly using javascript.

没有办法直接使用 javascript 来做到这一点。

Jquery has a couple of functions to keep track of that data.

Jquery 有几个函数来跟踪这些数据。

One "pure" way to do that is to change the addEventListener/attachEvent function through prototyping (search about javascript prototype stuff, not the framework).

一种“纯粹”的方法是通过原型设计更改 addEventListener/attachEvent 函数(搜索 javascript 原型内容,而不是框架)。

Or if you have a custom function to hadle adding/removing events you can tune it.

或者,如果您有一个自定义函数来处理添加/删除事件,您可以对其进行调整。

Well, that's it.

嗯,就是这样。

回答by NinjaCross

Of course ! Take a look at this to bind/unbind events http://api.jquery.com/category/events/and use this jQuery code fragment to get all the events bound to an element in the form of a hashset of keypairs "eventname/function delegate"

当然 !看看这个绑定/解除绑定事件 http://api.jquery.com/category/events/并使用这个 jQuery 代码片段以密钥对“eventname/”的哈希集形式获取绑定到元素的所有事件函数委托”

jQuery(elem).data('events');

回答by Gus

If you don't want ot use jQuery, a quick and dirty way (and there's bound to be a better one) would be to loop through the element's parameters and check for functions that begin with 'on' (onclick etc).

如果您不想使用 jQuery,一种快速而肮脏的方法(肯定会有更好的方法)是循环遍历元素的参数并检查以“on”(onclick 等)开头的函数。

var el = document.getElementById('elementid') ;
el.onclick = function(e) { console.log('Clicked!') ; } ; // Attached test event.
if(typeof(el)=='object') {
   for(var i in el) {
      if(i.substr(0,2) == 'on' && typeof(el[i])=='function') {
         el[i] = function() {} ; // Unbind with null function.
      }
   }
}