I have a click event on an element that changes it's class from "fave" to "faved", I am then trying to fire a new clicked event if the element is clicked when it's class is faved, but it is not firing, here is my javascript.
$("#jobwall .fave").click(function(){
var self = $(this);
$.ajax({
url: "/favourites/save_employer",
type: "POST",
data: "employer_id="+self.attr('href'),
success:function() {
开发者_StackOverflow中文版 self.removeClass('fave');
self.addClass('faved');
}
});
return false;
});
$(".faved").live("click", function(){
alert("!!");
return false;
});
You may include the .click() event to the new object, and not to use .live(). Like this:
$("#jobwall .fave").click(function(){
var self = $(this);
$.ajax({
url: "/favourites/save_employer",
type: "POST",
data: "employer_id="+self.attr('href'),
success:function() {
self.removeClass('fave');
self.addClass('faved');
self.click(function(){alert("!!"); return false;});
}
});
return false;
});
The .live() method is for adding elements, not changing. Remember this.
More information about .live() here.
Good luck :D
Update
As of jQuery 1.7, the .live()
method is deprecated. Use .on()
to attach event handlers.
From the messing around I did it looks as if those return false;
statements are getting in your way. You should really consider using event.preventDefault();
... as such:
$("#jobwall .fave").click(function(event){
event.preventDefault();
Check out this jsFiddle for an example as to what I mean
精彩评论