使用.one()和.live()jQuery

我在使用live()函数:

 $('a.remove_item').live('click',function(e) {}); 

我需要将其更改为one()以防止多次单击,但是当我在页面加载后注入其中一个元素时, one()侦听器不会触发。

如何让one()表现得像live()

试试这个:

 $('a.remove_item').live('click',function(e) { if($(e.target).data('oneclicked')!='yes') { //Your code } $(e.target).data('oneclicked','yes'); }); 

这会执行您的代码,但它也会将标记’oneclicked’设置为yes,这样它就不会再次激活。 基本上只需设置一个设置即可在单击一次后停止激活。

这是一个用于运行.live()处理程序的插件版本,纯粹是出于无聊而创建的:

 $.fn.liveAndLetDie = function(event, callback) { var sel = this.selector; function unbind() { $(sel).die(event, callback).die(event, unbind); } return this.live(event, callback).live(event, unbind); }; 

它就像.live()一样工作(除非你需要事件数据参数,在这种情况下你需要添加重载)。 只需以同样的方式使用它:

 $('a.remove_item').liveAndLetDie('click', function(e) { /* do stuff */ }); 

你可以在这里测试一下 。

只需在处理程序中使用jQuery的.die()方法 :

示例: http //jsfiddle.net/Agzar/

 $('a.remove_item').live('click',function(e) { alert('clicked'); $('a.remove_item').die('click'); // This removes the .live() functionality });​ 

编辑:

或者,如果您只想基于每个元素禁用事件,则可以更改类名,因为live()是基于选择器的。

示例: http //jsfiddle.net/Agzar/1/

 $('a.remove_item').live('click',function(e) { alert('i was clicked'); $(this).toggleClass('remove_item remove_item_clicked'); });​ 

这将类从remove_item更改为remove_item_clicked ,它可以具有相同的样式。 现在live()在第一次点击后不会激活。

试试这个

 $('a.remove_item').live('click', function(e) { if(!$(this).hasClass('clicked')) { $(this).addClass('clicked'); alert("dd"); // this is clicked once, do something here } });​ 

我知道这是一个旧post,但这对我来说类似的情况:

 $('a.remove_item').live('click', function(e) { e.stopPropagation(); // Your code here });​ 

我在$ .ajax函数上使用它,所以,在最后,在我的情况下失败,我使用500,以便延迟它并停止重发多次。

}).fail(function(response, status){ alert("FAILED: "+JSON.stringify(response, null, 4)); },500);

我希望它对你有所帮助!