jQuery $(this) 与 $.post() 的问题
所以这是我的代码,当用户单击关注按钮时:
$('.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);
});
});
它很高兴将其替换为第 2 行所示的加载 gif。但是当它返回数据并将其替换为第 4 行返回的数据时。
我该怎么办解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
$(this)
分配给$.post()
之外的变量:然后,而不是使用
$(this)
添加数据,使用我们刚刚创建的变量:再次查看您的代码,您还可以执行以下操作:
因为您已经拥有元素的
id
。Assign
$(this)
to a variable outside the$.post()
:Then, instead of using
$(this)
to add the data, use the variable we just created:Looking at your code again, you could also do this:
Since you already have the
id
of your element.在
$.post
内,this
不再是您的元素。您需要将其保存到$.post
之前的变量中。Inside
$.post
,this
is no longer your element. You need to save it to a variable before$.post
.$(this)
在$.post
范围内脱离了上下文。您需要将其缓存到变量中并在内部重用它。$(this)
is out of context inside the$.post
scope. You need to cache it into a variable and reuse it inside.