jquery防止分配重复的function

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

this.click(function(){ alert('test'); }) 

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

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

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

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

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

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

这里myApp是命名空间。

使用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) {...}); 

我想补充马吕斯的答案 –

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

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

这里’alert’是click事件的命名空间名称,只有与该命名空间绑定的函数才会被解除绑定。

假设元素正被添加到html中,并且您只想为添加的元素添加事件:

 function addEvents2Elements()//prevent Duplicate { //this will add the event to all elements of class="ele2addevent" $('.ele2addevent').not('.clickbind').on('click',function(){alert('once');}) //this will add a class an then the class="ele2addevent clickbind" $('.ele2addevent').not('.clickbind').addClass('.clickbind'); //all elements of class="... clickbind" will not be catched anymore in the first line because of .not() every time you call this function } addEvents2Elements(); 

你只能添加class =“ele2addevent”,因为在绑定之后它将是class =“ele2addevent clickbind”并且不再被捕获…