Possible jQuery bug - Event still being fired on changed Class element
I spotted a potential bug yesterday with jQuery in this code:
$(document).ready(function() {
$('.likedLink').click(function(){
return false;
});
$('.likes').click(function(){
var id = $(this).attr('id');
var currentLike = id;
id = id.replace('p','');
$.ajax({
type: "POST",
url: "/posts/like",
data: "id=" + id,
success: function(like){
$('#' + currentLike).html(like).removeClass开发者_如何学编程('likes').addClass('likedLink');
}
});
return false;
});
});
The post receives a number back and sets the HTML of the current clicked link to the new value. I then change the class on the element to avoid further clicking/AJAX-ing.
Now, the code worked and it received the new HTML and even changed the class correctly but the AJAX event was still fired when the user/me clicked it, but it was a different class so it shouldnt have fired!
Any ideas, or is this a bug with jQuery?
By the way, i fixed the code by changing .html()
to .replaceWith("<p>" + like + "</p>")
but i was very curious how this was happening
This is not a bug!
Your selector is only evaluated when you create it. Changing the class name later will not unbind the event.
You'll have to unbind it:
$.ajax({
type: "POST",
url: "/posts/like",
data: "id=" + id,
success: function(like){
$('#' + currentLike).html(like).unbind('click');
}
});
No need to even change the class name.
When you use click (shortcut for bind("click", handler);
), it attaches the handler to the element itself, so changing class or parent won't affect the handler. You can try $(".likes").live("click, handler);
which will only run that callback if the element still has that class
You need to use live() or delegate() instead of click(). The click() function assigns events once and does not check to see if they changed.
精彩评论