如何检查元素是否有点击处理程序? [英] How to check if element has click handler?

查看:100
本文介绍了如何检查元素是否有点击处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

测试事件处理程序是否绑定到jQuery中的元素

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

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

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

使用jquery-1.8.3

using jquery-1.8.3

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

So, how to check if element has click handler?

推荐答案

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

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

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

以下示例。

$(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>

另请注意,此事件检查事件仅在通过jQuery绑定事件时才有效。如果事件通过 element.attachEventListener 绑定, element.onclick < a onclick =doStuff()> 或任何其他非jQuery方式,这将无法正常工作。如果你适合这艘船,请查看这个答案

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.

这篇关于如何检查元素是否有点击处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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