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:
No need to even change the class name.