开发者

jQuery Getting original 'this' object

开发者 https://www.devze.com 2023-04-07 04:12 出处:网络
I\'m creating a follow button, and I\'m switching the class names to give the button a different look.

I'm creating a follow button, and I'm switching the class names to give the button a different look.

Unfortunately, my classes don't seem to be being swapped because the 'this' object appears to be changing in the code.

How do I get the original object that I selected so that I can swap the classes?

// Follow button
$('input.follow_user_button').live('click', 开发者_如何学JAVAfunction() {

        $.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.");
            }
        });

    });

Kind regards,

Luke


You should store the $(this) before the $.ajax, e.g.

var self = $(this);

$.ajax({ ...
   success: function()
   {
      self.attr(...);
   }
});

Don't use the $(this) too many times, this is overkill to do, put it into a variable, then use it for later reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消