Using .one() with .live() jQuery

前端 未结 6 2017
感动是毒
感动是毒 2020-12-09 04:32

I was using the live() function:

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

I needed to change this to one()

相关标签:
6条回答
  • 2020-12-09 04:39

    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.

    0 讨论(0)
  • 2020-12-09 04:44

    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 讨论(0)
  • 2020-12-09 04:50

    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
    });​
    
    0 讨论(0)
  • 2020-12-09 04:51

    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.

    0 讨论(0)
  • 2020-12-09 05:00

    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.

    0 讨论(0)
  • 2020-12-09 05:02

    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
        }
    });​
    
    0 讨论(0)
提交回复
热议问题