0

My DOM structure is as follows,

<a id='c_1' class='like'>Like</a>
<a id='c_2' class='like'>Like</a>
<a id='c_3' class='like'>Like</a>
......

Binding click event as follows,

$(document).on("click",".like",function(){
      var selector = $(this);
      saveLikes(selector);       
});

saveLikes(selector) have Ajax call,on success of Ajax call I want to remove/unbind click event on currently clicked element for that I've written following code in success callback.

$(document).off("click",selector);

It's not working and I'm able to remove click event by $(document).off("click",".like"); but I don't want this because further clicks on other elements will not fire the event.

Is their any solution to remove event on current element only that too without changing class name ?

Mahesh.D
  • 1,691
  • 2
  • 23
  • 49

5 Answers5

2

In this case you

$(document).on("click",".like",function(){
    var selector = $(this);
    if(selector.data('liked')){
        return;
    }

    saveLikes(selector);     
    selector.data('liked', true)
});

Or

$(document).on("click",".like:not(.liked)",function(){
    var selector = $(this).addClass('liked');
    saveLikes(selector);     
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

This one...

$('#foo').unbind('click', function() {
    alert('The quick brown fox jumps over the lazy dog.');
});

REFERENCE: .unbind()

Olrac
  • 1,527
  • 2
  • 10
  • 22
1

Maybe this would help

$( "#foo" ).one( "click", function(){
    alert( "This will be displayed only once.");
});

The Click event is executed just once for that particular ID and unbinds it automatically.

REFERENCE: .one()

cfi
  • 10,915
  • 8
  • 57
  • 103
0

Updated code

$(".like").click(function() {
    var selector = $(this);
    saveLikes(selector);
    selector.off('click');       // <- Put this in Ajax success
});
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21
0

If you want to add click event once then you can use one() for this,

like,

$('.like').one("click",function(){
      var selector = $(this);
      saveLikes(selector);       
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106