我正在创建一个关注按钮,我正在切换类名,使按钮看起来不同。
不幸的是,我的类似乎没有被交换,因为'this'对象似乎在代码中发生了变化。
如何获取我选择的原始对象以便我可以交换类?
// Follow button
$('input.follow_user_button').live('click', function() {
$.ajax({
type: "POST",
url: "ajax/follow.php",
data: {
follow_user_id: $(this).attr('data-follow-user-id')
},
dataType: "json",
success: function(follow_response) {
if (follow_response.result == "success")
{
if (follow_response.action == "success_follow")
{
// Set the follow button to followed class style THIS DOESNT WORK
$(this).attr('value', 'Unfollow').removeClass('follow_button_follow').addClass('follow_button_unfollow');
}
else if (follow_response.action == "deleted_follow")
{
// Set the follow button to the unfollowed class style THIS DOESNT WORK
$(this).attr('value', 'Follow').removeClass('follow_button_unfollow').addClass('class', 'follow_button_follow');
}
}
else if (follow_response.result == "failure")
{
alert(follow_response.error_message);
}
},
error: function() {
alert("Sorry there was an error, please refresh and try again.");
}
});
});
亲切的问候,
路
答案 0 :(得分:4)
您应该在$(this)
之前存储$.ajax
,例如
var self = $(this);
$.ajax({ ...
success: function()
{
self.attr(...);
}
});
不要多次使用$(this)
,这样做太过分了,把它放到一个变量中,然后用它来供以后参考。