【问题标题】:jQuery $(this) problems with $.post()jQuery $(this) 与 $.post() 的问题
【发布时间】:2011-12-30 22:27:17
【问题描述】:
所以这是我的代码,用于当用户点击关注按钮时:
$('.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行返回的数据。
我该如何解决这个问题?
【问题讨论】:
标签:
jquery
html
ajax
this
【解决方案1】:
将$(this)分配给$.post()之外的变量:
var $this = $(this);
然后,不要使用$(this)添加数据,而是使用我们刚刚创建的变量:
$this.html(data);
再次查看您的代码,您也可以这样做:
$("#" + userId).html(data);
因为您已经拥有元素的id。
【解决方案2】:
在$.post 内部,this 不再是您的元素。您需要将其保存到$.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) 在$.post 范围内脱离上下文。您需要将其缓存到变量中并在其中重复使用。
$('.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)
});
});