Javascript 如何检查元素是否具有点击处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14072042/
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-08-24 15:38:47  来源:igfitidea点击:

How to check if element has click handler?

javascriptjqueryjavascript-events

提问by kostepanych

Possible Duplicate:
test if event handler is bound to an element in jQuery

可能的重复:
测试事件处理程序是否绑定到 jQuery 中的元素

Tried to do the following (link is jQuery object of 'a' tag):

尝试执行以下操作(链接是 'a' 标签的 jQuery 对象):

 link.data("events") //undefined even if link has event handlers
 jQuery.data(link, 'events') //undefined always also
 jQuery._data(link, 'events') //undefined always also

using jquery-1.8.3

使用 jquery-1.8.3

So, how to check if element has click handler?

那么,如何检查元素是否有点击处理程序?

回答by Snuffleupagus

You can use jQuery._datato check for events. The first argument should be a reference to the HTML element, not the jQuery object.

您可以使用jQuery._data来检查事件。第一个参数应该是对 HTML 元素的引用,而不是 jQuery 对象。

var ev = $._data(element, 'events');
if(ev && ev.click) alert('click bound');

Sample below.

示例如下。

$(function(){
    $('#test').click(function(){
        // NOTE: this below is refering to the HTML element, NOT the jQuery element
        var ev = $._data(this, 'events');
        if(ev && ev.click) alert('click bound to this button');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button id="test">Click me to check for click handlers</button>

Also note that this method for checking events will only work when the event is bound via jQuery. If the event is bound via element.attachEventListener, element.onclick, <a onclick="doStuff()">or any other non jQuery way, this will not work. If you're fitting into this boat, check this answer.

另请注意,此检查事件的方法仅在通过 jQuery 绑定事件时才有效。如果该事件是通过约束element.attachEventListenerelement.onclick<a onclick="doStuff()">或者任何其他非jQuery的方式,这是不行的。如果您适合这艘船,请查看此答案