jQuery 只绑定一次事件

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

bind event only once

jquery

提问by firebird

I have the following code:

我有以下代码:

function someMethod()
{
  $(obj).click(function {});
}

someMethod is called twice and thus click event is binded twice. How can I make it bind only once?

someMethod 被调用两次,因此 click 事件被绑定两次。我怎样才能让它只绑定一次?

回答by pna

If you can apply it, probably want to take a look at event.preventDefaultand event.stopPropagationOR unbind and bind each time, within your method like

如果你可以应用它,可能想看看event.preventDefaultevent.stopPropagation或者每次都取消绑定和绑定,在你的方法中

function someMethod()
{
  $(obj).off('click').on('click', function(e) {
    // put your logic in here 
  });
}

回答by Iain

In addition to pna's answer you may wish to think about namespacing your event so you do not go around unbinding all the click events accidentally.

除了 pna 的答案之外,您可能还希望考虑为您的事件命名空间,这样您就不会意外地解除所有点击事件的绑定。

function someMethod() {
    $(obj).unbind('click.namespace').bind('click.namespace', function() { });
}

https://api.jquery.com/event.namespace/

https://api.jquery.com/event.namespace/

回答by Matt Paxton

There is no built in method to determine if you have already bound this particular function. You can bind multiple click functions to an object. For example:

没有内置方法来确定您是否已经绑定了这个特定的函数。您可以将多个点击功能绑定到一个对象。例如:

$('#id').bind('click', function(){
alert('hello');
});


$('#id').bind('click', function(){
alert('goodbuy');
});

if you do the above when the object is clicked it will alert hello then goodbye. To make sure only one function is bound to the click event unbind the click event handler then bind the desired function like this:

如果您在单击对象时执行上述操作,它将提醒您好,然后再见。为了确保只有一个函数绑定到 click 事件,请取消绑定 click 事件处理程序,然后像这样绑定所需的函数:

$(obj).unbind('click').bind('click', function(){... });

回答by jfriend00

The obvious solution is to not call someMethod()twice. If you can't fix that, then you can keep a state variable so it only ever binds once like this:

显而易见的解决方案是不要调用someMethod()两次。如果你不能解决这个问题,那么你可以保留一个状态变量,这样它只会像这样绑定一次:

function someMethod()
{
    if (!someMethod.bound) {
        $(obj).click(function() {});
        someMethod.bound = true;
    }
}

Note: this uses a property of the function itself rather than introducing a global variable to keep track of whether it's been bound. You could also use a property on the object itself.

注意:这使用函数本身的属性而不是引入全局变量来跟踪它是否被绑定。您还可以在对象本身上使用属性。

You can see it work here: http://jsfiddle.net/jfriend00/VHkxu/.

你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/VHkxu/

回答by xandrw

Or use jQuery's one() function which is similar to on() but only fires the event once, even if you bind it multiple times.

或者使用 jQuery 的 one() 函数,它类似于 on() 但只触发一次事件,即使您多次绑定它。

http://api.jquery.com/one/

http://api.jquery.com/one/

回答by Esailija

jQuery makes calling some function possible only once pretty easy:

jQuery 使得某些函数只调用一次非常容易:

function someMethod()
{

     $(obj).click(function() {});
      this.someMethod = $.noop;
}

回答by Bamboo

This is a suggestion since I do not know your logic. May or may not work for you.

这是一个建议,因为我不知道你的逻辑。可能适合您,也可能不适合您。

Try combining jquery live() and one() functions will give you a better result than event rebinds.

尝试结合 jquery live() 和 one() 函数会给你一个比事件重新绑定更好的结果。

The special cases work when you have 2 DOM elements (parent & child). Live() at parent node makes sure event will be invoked, and then calls one() to dynamically register event which would be executed only once. (this provides similar functionality like rebinds).

当您有 2 个 DOM 元素(父元素和子元素)时,特殊情况会起作用。父节点的 Live() 确保事件将被调用,然后调用 one() 动态注册仅执行一次的事件。(这提供了类似的功能,如重新绑定)。

回答by Bakyt Abdrasulov

You can add css class to the binded elements and then filter them out:

您可以将 css 类添加到绑定元素,然后将它们过滤掉:

function someMethod()
{
    $(obj).not('.click-binded')
          .click(function {})
          .addClass('click-binded');
}

This method may be used also for plugins:

此方法也可用于插件:

  $(obj).not('.datetimepicker-applied')
        .datetimepicker()
        .addClass('datetimepicker-applied');

回答by nathnolt

You can use this jQuery extension function.

您可以使用这个 jQuery 扩展功能。

$.fn.once = function (type, fn, uid) {
  if(uid == undefined) {
    console.error("Called $.once without uid\n", this, "\n", fn);
  }

  var dataStr = type+"-handler-"+uid;
  if(!this.data(dataStr)) {
    this.data(dataStr, true);
    this.on(type, fn);
  }
};

Instead of doing this

而不是这样做

$("button").on("click", function(){
  alert("You Clicked On A Button");
});

Ya do this

你这样做

$("button").once("click", function(){
  alert("You Clicked On A Button");
}, "btnHandler");

Now when I have a function around it

现在当我有一个功能时

function addBtnHandler() {
  $("button").once("click", function() {
    alert("You Clicked On A Button");
  }, "btnHandler");
}

And I call it multiple times

我多次调用它

addBtnHandler();
addBtnHandler();
addBtnHandler();

It only does it once.

它只做一次。

Notice that the extension works by checking both uid and type. This means that you can bind different types of handlers with the same uid, you may or may not want this. To change it edit.

请注意,扩展程序通过检查 uid 和类型来工作。这意味着您可以使用相同的 uid 绑定不同类型的处理程序,您可能需要也可能不想这样做。要更改它编辑。

var dataStr = type+"-handler-"+uid;

var dataStr = type+"-handler-"+uid;

With something like

像这样的东西

var dataStr = "handler-"+uid;

var dataStr = "handler-"+uid;

回答by Ankit Vishwakarma

I was also trying to use off and on method of jquery for binding event only once with the dom element which does not exists yet or the dom element is not yet created.

我还尝试使用 jquery 的 off 和 on 方法仅将事件与尚不存在的 dom 元素或尚未创建的 dom 元素绑定一次。

$('.select').off('event').on('event', 'selector', function(e){ // });

This code was not working properly

此代码无法正常工作

I came across a very lucrative method that is 'one' method. It is very useful when you want to bind an event only once.

我遇到了一种非常有利可图的方法,即“单一”方法。当您只想绑定一个事件一次时,它非常有用。

You can find the document here http://api.jquery.com/one/

你可以在这里找到文档 http://api.jquery.com/one/

This is same as method 'on' but different with its behavior with not to stick with the event for multiple selectors.

这与方法 'on' 相同,但不同的是它的行为不坚持多个选择器的事件。

$('body').one('click', 'selector', function(){ // do your stuff here });