2011-12-30 42 views
0

因此,这里是我的,当用户点击一个后续按钮代码:

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

这是很高兴的加载GIF来取代它,如上线2.但是,当它返回数据并将其替换为第4行返回的数据时。

如何解决此问题?

+0

重复[$(this)在函数中不起作用](http://stackoverflow.com/questions/7859558/this-doesnt-work-in-a-function),[$(这个)对象在jquery post()之后变得未定义(许多其他的东西)(http://stackoverflow.com/questions/8422872/this-object-becomes-undefined-after-a-jquery-post)。 – 2011-12-30 22:43:18

回答

7

分配$(this)$.post()外部变量:

var $this = $(this); 

然后,而不是使用$(this)添加数据,使用刚创建的变量:

$this.html(data); 

看着你的代码再次,你也可以这样做:

$("#" + userId).html(data); 

既然你已经有了你的元素的id

2

Inside $.postthis不再是你的元素。您需要在$.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); 
    }); 
}); 
1

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