jQuery $(this) problems with $.post()

核能气质少年 提交于 2019-12-13 19:19:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!