如何检查click事件是否已绑定-JQuery [英] How to check if click event is already bound - JQuery
问题描述
我将点击事件与按钮绑定在一起:
I am binding a click event with a button:
$('#myButton').bind('click', onButtonClicked);
在一种情况下,该调用被多次调用,所以当我执行trigger
时,我看到了多个我想防止的ajax调用.
In one scenario, this is getting called multiple times, so when I do a trigger
I see multiple ajax calls which I want to prevent.
只有在未绑定bind
的情况下,才应如何操作.
How do I bind
only if its not bound before.
推荐答案
2012年8月24日更新:在jQuery 1.8中,不再可以使用.data('events')
访问元素的事件. (有关详细信息,请参见此错误.)可以使用jQuery._data(elem, 'events')
访问相同的数据,内部数据结构,未记录,因此不能保证100%保持稳定.但是,这应该不成问题,并且上面插件代码的相关行可以更改为以下内容:
Update 24 Aug '12: In jQuery 1.8, it is no longer possible to access the element's events using .data('events')
. (See this bug for details.) It is possible to access the same data with jQuery._data(elem, 'events')
, an internal data structure, which is undocumented and therefore not 100% guaranteed to remain stable. This shouldn't, however, be a problem, and the relevant line of the plugin code above can be changed to the following:
var data = jQuery._data(this[0], 'events')[type];
jQuery事件存储在名为events
的数据对象中,因此您可以在其中进行搜索:
jQuery events are stored in a data object called events
, so you could search in this:
var button = $('#myButton');
if (-1 !== $.inArray(onButtonClicked, button.data('events').click)) {
button.click(onButtonClicked);
}
当然,如果可以构建应用程序,使该代码仅被调用一次,那将是最好的选择.
It would be best, of course, if you could structure your application so this code only gets called once.
可以将其封装到插件中
$.fn.isBound = function(type, fn) {
var data = this.data('events')[type];
if (data === undefined || data.length === 0) {
return false;
}
return (-1 !== $.inArray(fn, data));
};
然后您可以致电:
var button = $('#myButton');
if (!button.isBound('click', onButtonClicked)) {
button.click(onButtonClicked);
}
这篇关于如何检查click事件是否已绑定-JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!