jQuery 获取附加到元素的所有事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18116163/
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
Get all events handlers attached to an element
提问by Mohamed Omezzine
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"
我需要找到所有附加到 #mySelect 的事件处理程序,如果事件是通过 jQuery 创建的,我可以得到它,这里 alert(e) 将只显示“更改”而不显示“单击”
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>
回答by RobG
The short answer is that it's not possible to reliably determine all the listeners on an element just using javascript.
简短的回答是,仅使用 javascript 不可能可靠地确定元素上的所有侦听器。
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 addEventListeneror attachEventunless a reference has been kept somewhere and it's made available (see comment about libraries).
长的答案是没有标准机制来列出所有附加的侦听器。一些库保留了使用该库附加的侦听器列表,但不一定知道其他侦听器。可以通过测试相关的元素属性和属性(对每个元素的onclick、onchange、onblur等进行一些繁琐的测试)来找到在标记中添加或作为元素属性添加的侦听器。但是不可能找到使用addEventListener或attachEvent添加的侦听器,除非引用已保存在某处并使其可用(请参阅有关库的评论)。
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.
此外,还有一些“委托”侦听器,它们看起来像是附加到元素上,但实际上它们附加到父元素上。
回答by Yuan Zhaohao
$( '#mySelect' ).bind( {
'change': function( event ) {
},
'click': function( event ) {
}
});
$.each($._data( $("#mySelect")[0], "events" ), function(e) {
alert(e);
});
回答by nico
In addition for events attached inline you can try this:
除了内联附加的事件,您还可以尝试以下操作:
alert(document.getElementById('mySelect').getAttribute('onclick'));