JQuery 未知 "this" 内 ajax 请求

JQuery unknown "this" inside ajax request

我需要在发出 ajax 请求后更改 class 属性,但我无法在 Ajax 请求

中访问 "this"
$('.shopping').click(function(){
        //Get id attribute
        var id = $(this).attr('id');

        //Send id attribute in Ajax request
        $.get('processAddToShopping.php?id='+id, function(data){
        if(data == "success"){
           //Change attribute if success
           $(this).attr('class', 'new'); //CAN'T access "this" anymore
        }
        });
});

设置上下文变量:

$('.shopping').click(function(){
    //Get id attribute
    var id = $(this).attr('id');
    var that = this;

    //Send id attribute in Ajax request
    $.get('processAddToShopping.php?id='+id, function(data){
        if(data == "success"){
       //Change attribute if success
            $(that).attr('class', 'new'); 
        }
    });
});

因为你已经有了 'id' 属性,你可以通过 id 找到 DOM 元素:)

 $("#"+id).attr('class', 'new');