How to check if element has click handler? [duplicate]

梦想与她 提交于 2019-12-17 23:18:36

问题


Possible Duplicate:
test if event handler is bound to an element in 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

using jquery-1.8.3

So, how to check if element has click handler?


回答1:


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');

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.



来源:https://stackoverflow.com/questions/14072042/how-to-check-if-element-has-click-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!