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

Tit*_*tan 17 jquery

我正在使用这个live()功能:

$('a.remove_item').live('click',function(e) {});
Run Code Online (Sandbox Code Playgroud)

我需要改变这对one()防止多次点击,但是当我注入后的页面加载了这些元素之一one()听者不火.

我怎么能one()表现得像live()

ego*_*ard 15

试试这个:

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

这会执行你的代码,但它也将"oneclicked"作为是一个标志,所以它不会再次激活.基本上只是设置一个设置,从一旦它被点击一次激活停止.


Nic*_*ver 15

这是一个运行.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);
};
Run Code Online (Sandbox Code Playgroud)

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

$('a.remove_item').liveAndLetDie('click', function(e) { /* do stuff */ });
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下.


use*_*716 11

只需在处理程序中使用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
});?
Run Code Online (Sandbox Code Playgroud)

编辑:

Or if you only wanted to disable the event on a per-element basis, you could just change the class name since live() is selector-based.

Example: http://jsfiddle.net/Agzar/1/

$('a.remove_item').live('click',function(e) {
    alert('i was clicked');
    $(this).toggleClass('remove_item remove_item_clicked');
});?
Run Code Online (Sandbox Code Playgroud)

This changed the class from remove_item to remove_item_clicked which could have the same styling. Now live() will not fire after the first click.