Ajax see the old class
I've this:
$(".follow").click(function() {
var element = $(this);
var id = element.attr("id");
var data = "id=" + id;
$.ajax({
type: "POST",
url: "follow.php",
data: data,
success: function(result) {
element.removeClass("follow");
element.addClass("unfollow");
}
});
return false;
});
$(".unfoll开发者_运维知识库ow").click(function() {
alert("Hey, dude");
});
When I click on my button I can see with Firebug the class switch. But if I try to click the button again, it doesn't appear the alert, the script send always the POST request to follow.php.
Why?
You need to use .live('click', ...)
instead of .click(...)
. The former works for all elements matching that selector, now and in the future, whereas the latter only works for elements matching the selector right now.
It's not a matter of ajax "seeing" the old class, it's how the event listeners are bound. $(".follow").click(callback)
finds all the elements in the DOM that have the class follow
, and then binds callback
to the click
event of every such element. Removing the follow
class does not remove event listeners.
.live()
also binds only one listener, rather than one listener per element in the jQuery object, so it is more "efficient" (read: lighter weight) in that regard.
$(".follow").live("click", function() {
var element = $(this),
data = "id=" + this.id;
$.ajax({
type: "POST",
url: "follow.php",
data: data,
success: function(result) {
element.removeClass("follow").addClass("unfollow");
}
});
return false;
});
$(".unfollow").live("click", function() {
alert("Hey, dude");
});
Notes
- You can, and should, use
this.id
instead of$(this).attr("id")
. See When to use Vanilla JavaScript vs. jQuery? - Take advantage of jQuery's chainability for more efficient, concise code.
精彩评论