Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove event on on();

Tags:

jquery

I'm having problem unbinding event from an element which I assigned an event to using on();

Here is my JS:

    $(document).on('click','.reply-indicator a', function(e){
    e.preventDefault();
    var commentid = $(this).data('commentid');
    $.ajax({
        type: 'POST',
        url: '?category=getreplies',
        data:{
            "commentid" : commentid
        },
        success: function(data){
            $('.'+commentid+'subcomments').append(data);
        }
    });
    return false;
});

I've tried everything I could think off to remove the click event from the element I even assigned an id attribute each iteration to each element to be able to target the element specifically because there are several:

$(document).off('click','#'+commentid+'indicator a');
$('#'+commentid+'indicator a').off();

$('#'+commentid+'indicator a').off('click');

$('#'+commentid+'indicator a').unbind('click');

But It wont loose the event in the callbackfunction or not even when I try putting this code before the ajax request but the event is still working after the callback function. Am I trying to target it correctly?

like image 335
user1683645 Avatar asked Dec 04 '25 18:12

user1683645


1 Answers

Try adding a class to the elements you want the delegate on and then when you want to remove certain elements just remove the class

//add delegate
$(document).on('click','.reply-indicator a.onclick', function(e){
...
//remove the class from the element so it no loger matches the delegate selector
$('#'+commentid+'indicator a').removeClass('onclick');

http://jsfiddle.net/jN7LG/2/

like image 188
Musa Avatar answered Dec 07 '25 09:12

Musa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!