获取附加到元素的所有事件处理程序 [英] Get all events handlers attached to an element

查看:93
本文介绍了获取附加到元素的所有事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到所有附加到#mySelect的事件处理程序,如果该事件是通过jQuery创建的,我可以获取它,在这里alert(e)将仅显示更改"而没有单击"

I need to find all events handlers attached to #mySelect and if the event is created via jQuery I can get it , here alert(e) will show only "change" without "click"

JavaScript:

JavaScript :

$("#mySelect").change(function(){
    alert("changed");
})           
$.each($._data(  $("#mySelect")[0], "events" ), function(e) {
    alert(e);
})

HTML:

<select id="mySelect" onclick="alert('hello')" >
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
</select>

推荐答案

简短的答案是,仅使用JavaScript不可能可靠地确定元素上的所有侦听器.

The short answer is that it's not possible to reliably determine all the listeners on an element just using javascript.

长答案是没有列出所有连接的侦听器的标准机制.一些库保留使用该库已附加的侦听器列表,但不一定了解其他侦听器.可以通过测试相关的元素属性和属性来找到添加在标记中或作为元素属性的侦听器(对 onclick onchange onblur 进行一些繁琐的测试) ,等等).但是,除非找到引用保留在某个地方并且使引用可用(请参阅有关库的注释),否则不可能找到使用 addEventListener attachEvent 添加的侦听器.

The long answer is that there is no standard mechanism to list all attached listeners. Some libraries keep a list of listeners that have been attached using the library, but don't necessarily know about other listeners. Listeners added in the markup or as element properties can be found by testing related element properties and attributes (somewhat tedious testing for onclick, onchange, onblur, etc. for each element). But it's impossible to find a listener added using addEventListener or attachEvent unless a reference has been kept somewhere and it's made available (see comment about libraries).

此外,有委派的"侦听器在实际上附加到父元素的情况下,看起来像是附加在元素上.

Also, there are "delegated" listeners that give the appearance of being attached to an element when in fact they are attached to a parent element.

这篇关于获取附加到元素的所有事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆