问题
So here's my code for when a user clicks a follow button:
$('.follow_btn').click(function() {
$(this).html('<img src = "../assets/style_images/loading.gif">');
var userId = $(this).attr('id');
$.post('../assets/scripts/ajax_follow_parse.php', {
userId: userId
}, function(data) {
$(this).html(data);
});
});
It is quite happy to replace it with the loading gif as shown on line 2. But when it returns the data and replace it with the data returned on line 4.
How can I fix this?
回答1:
Assign $(this)
to a variable outside the $.post()
:
var $this = $(this);
Then, instead of using $(this)
to add the data, use the variable we just created:
$this.html(data);
Looking at your code again, you could also do this:
$("#" + userId).html(data);
Since you already have the id
of your element.
回答2:
Inside $.post
, this
is no longer your element. You need to save it to a variable before $.post
.
$('.follow_btn').click(function () {
var $this = $(this); // Save this, so it can be used inside $.post
$this.html('<img src = "../assets/style_images/loading.gif">');
var userId = $this.attr('id');
$.post('../assets/scripts/ajax_follow_parse.php', { userId: userId }, function(data) {
$this.html(data);
});
});
回答3:
$(this)
is out of context inside the $.post
scope. You need to cache it into a variable and reuse it inside.
$('.follow_btn').click(function () {
$this = $(this);
$this.html('<img src = "../assets/style_images/loading.gif">');
var userId = $this.attr('id');
$.post('../assets/scripts/ajax_follow_parse.php', { userId: userId }, function(data) {
$this.html(data); //$this not $(this)
});
});
来源:https://stackoverflow.com/questions/8684669/jquery-this-problems-with-post