jquery防止分配重复的功能

Rog*_*ger 24 jquery function dynamic click

如果我需要动态分配点击功能,有没有办法确保点击功能只分配一次而不重复?

this.click(function(){
    alert('test');
})
Run Code Online (Sandbox Code Playgroud)

Mar*_*ius 44

您可以在再次绑定之前取消绑定click事件,这样您只会附加一个事件:

//assuming this is a jquery object.
this.unbind("click");
this.click(function(){
  alert("clicked once");
});
Run Code Online (Sandbox Code Playgroud)

从jQuery 1.7开始,单击现在使用.on(http://api.jquery.com/click/),所以现在正确的代码

//assuming this is a jquery object.
this.off("click");
this.click(function(){
  alert("clicked once");
});
Run Code Online (Sandbox Code Playgroud)

这将取消绑定所有单击事件(包括您可能正在使用的任何插件创建的事件).确保您只解除对事件使用命名空间的绑定.(http://api.jquery.com/off/)

//assuming this is a jquery object.
this.off("click.myApp");
this.on("click.myApp", function(){
  alert("clicked once");
});
Run Code Online (Sandbox Code Playgroud)

这里myApp是命名空间.


sie*_*ppl 15

使用jQuery .on(),您可以执行以下操作:

//removes all binding to click for the namespace "myNamespace"
$(document).off('click.myNamespace'); 

$(document).on('click.myNamespace', '.selector', function(event) {...}); 

//this will be also removed (same namespace)
$(document).on('click.myNamespace', '.anotherSelector', function(event) {...}); 
Run Code Online (Sandbox Code Playgroud)


Muh*_*uhd 9

我想补充马吕斯的回答 -

在避免重复绑定时,如果应该有多个绑定到事件的函数,则不希望意外取消绑定.当您与多个开发人员合作时,这一点尤为重要.要防止这种情况,您可以使用事件命名空间:

//assuming this is a jquery object.
var alertEvent = 'click.alert'
this.unbind(alertEvent).bind(alertEvent,function(){
  alert('clicked once');
});
Run Code Online (Sandbox Code Playgroud)

这里戒备"是命名空间点击事件并用该名称空间势必会绑定只有你的函数的名称.