且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 14:48:04

您可以使用 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.