开发者

Using .one() with .live() jQuery

I was using the live() function:

$(开发者_开发百科'a.remove_item').live('click',function(e) {});

I needed to change this to one() to prevent multiple clicks, however when I inject one of these elements after the page has loaded the one() listener does not fire.

How can I get one() to behave like live()?


Try this:

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

This executes your code, but it also sets a flag 'oneclicked' as yes, so that it will not activate again. Basically just sets a setting to stop it from activating once it's been clicked once.


Here's a plugin version for running a .live() handler once, created purely out of boredom:

$.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);
};

It works just like .live() would (unless you need the event data argument, in which case you'd need to add the overload). Just use it the same way:

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

You can test it out here.


Just use jQuery's .die() method in the handler:

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

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

EDIT:

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');
});​

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.


Try this

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


I know this is an old post, but this worked for me on a similar case:

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


I use it on $.ajax function, so, on the final, in my case fail, I use ,500 in order to delay it and stop to resend many times.

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

I hope it helps you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜