如何检查点击事件是否已经绑定 - JQuery

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

How to check if click event is already bound - JQuery

jquery

提问by Dusty

I am binding a click event with a button:

我正在用一个按钮绑定一个点击事件:

$('#myButton').bind('click',  onButtonClicked);

In one scenario, this is getting called multiple times, so when I do a triggerI see multiple ajax calls which I want to prevent.

在一种情况下,这会被多次调用,因此当我执行 a 时,我会trigger看到多个想要阻止的 ajax 调用。

How do I bindonly if its not bound before.

bind仅当它之前未绑定时我该怎么办。

采纳答案by lonesomeday

Update 24 Aug '12: In jQuery 1.8, it is no longer possible to access the element's events using .data('events'). (See this bugfor 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:

2012年 8 月 24 日更新:在 jQuery 1.8 中,不再可能使用.data('events'). (有关详细信息,请参阅此错误。)可以使用jQuery._data(elem, 'events')内部数据结构访问相同的数据,该结构没有记录,因此不能 100% 保证保持稳定。但是,这应该不是问题,上面插件代码的相关行可以更改为以下内容:

var data = jQuery._data(this[0], 'events')[type];


jQuery events are stored in a data object called events, so you could search in this:

jQuery 事件存储在名为 的数据对象中events,因此您可以在此搜索:

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.

当然,如果您可以构建您的应用程序以便此代码仅被调用一次,那将是最好的。



This could be encapsulated into a plugin:

这可以封装成一个插件:

$.fn.isBound = function(type, fn) {
    var data = this.data('events')[type];

    if (data === undefined || data.length === 0) {
        return false;
    }

    return (-1 !== $.inArray(fn, data));
};

You could then call:

然后你可以调用:

var button = $('#myButton');
if (!button.isBound('click', onButtonClicked)) {
    button.click(onButtonClicked);
}

回答by Konrad Garus

One more way - mark such buttons with a CSS class and filter:

另一种方法 - 使用 CSS 类和过滤器标记此类按钮:

$('#myButton:not(.bound)').addClass('bound').bind('click',  onButtonClicked);

In recent jQuery versions replace bindwith on:

在最近的 jQuery 版本中替换bindon

$('#myButton:not(.bound)').addClass('bound').on('click',  onButtonClicked);

回答by Naftali aka Neal

If using jQuery 1.7+:

如果使用 jQuery 1.7+:

You can call offbefore on:

您可以off在之前致电on

$('#myButton').off('click', onButtonClicked) // remove handler
              .on('click', onButtonClicked); // add handler

If not:

如果不:

You can just unbind it first event:

您可以在第一个事件中解除绑定:

$('#myButton').unbind('click', onButtonClicked) //remove handler
              .bind('click', onButtonClicked);  //add handler

回答by Rodolfo Jorge Nemer Nogueira

I wrote a very tiny plugin called "once" which do that. Execute off and on in element.

我写了一个名为“once”的非常小的插件来做到这一点。在元素中执行关闭和开启。

$.fn.once = function(a, b) {
    return this.each(function() {
        $(this).off(a).on(a,b);
    });
};

And simply:

简单地说:

$(element).once('click', function(){
});

回答by Pablonete

The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.

我看到的最好方法是使用 live() 或 delegate() 在父元素中而不是在每个子元素中捕获事件。

If your button is inside a #parent element, you can replace:

如果您的按钮位于 #parent 元素内,您可以替换:

$('#myButton').bind('click', onButtonClicked);

$('#myButton').bind('click', onButtonClicked);

by

经过

$('#parent').delegate('#myButton', 'click', onButtonClicked);

$('#parent').delegate('#myButton', 'click', onButtonClicked);

even if #myButton doesn't exist yet when this code is executed.

即使在执行此代码时 #myButton 还不存在。

回答by Krillehbg

Why not use this

为什么不使用这个

unbind()before bind()

unbind()bind()

$('#myButton').unbind().bind('click',  onButtonClicked);

回答by Yair Galler

Here's my version:

这是我的版本:

Utils.eventBoundToFunction = function (element, eventType, fCallback) {
    if (!element || !element.data('events') || !element.data('events')[eventType] || !fCallback) {
        return false;
    }

    for (runner in element.data('events')[eventType]) {
        if (element.data('events')[eventType][runner].handler == fCallback) {
            return true;
        }

    }

    return false;
};

Usage:

用法:

Utils.eventBoundToFunction(okButton, 'click', handleOkButtonFunction)

回答by A. Morel

To avoid to check/bind/unbind, you can change your approach! Why don't you use Jquery .on() ?

为了避免检查/绑定/解除绑定,你可以改变你的方法!你为什么不使用 Jquery .on() ?

Since Jquery 1.7, .live(), .delegate() is deprecated, now you can use .on() to

由于 Jquery 1.7、.live()、.delegate() 已弃用,现在您可以使用 .on() 来

Attach an event handler for all elements which match the current selector, now and in the future

现在和将来与当前选择器匹配的所有元素附加一个事件处理程序

It means that you can attach an event to a parent element that is still existing and attach children elements whether they are present or not!

这意味着您可以将事件附加到仍然存在的父元素,并附加子元素,无论它们是否存在!

When you use .on() like this:

当您像这样使用 .on() 时:

$('#Parent').on('click', '#myButton'  onButtonClicked);

You catch event click on parent and it search child '#myButton' if exists...

您在父级上捕获事件单击,如果存在,它会搜索子级“#myButton”...

So when you remove or add a child element, you do not have to worry about whether to add or remove the event binding.

所以当你移除或添加子元素时,你不必担心是否添加或移除事件绑定。

回答by ariel

Based on @konrad-garus answer, but using data, since I believe classshould be used mostly for styling.

基于@konrad-garus 的回答,但使用data, 因为我认为class应该主要用于造型。

if (!el.data("bound")) {
  el.data("bound", true);
  el.on("event", function(e) { ... });
}

回答by Mukhtiar Zamin

Try:

尝试:

if (typeof($("#myButton").click) != "function") 
{
   $("#myButton").click(onButtonClicked);
}