JQuery在ajax请求中未知“this”

时间:2015-01-22 14:40:28

标签: jquery ajax

我需要在创建ajax请求时更改class属性,但我无法访问"这个"在Ajax请求中

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

2 个答案:

答案 0 :(得分:3)

设置上下文变量:

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

答案 1 :(得分:0)

由于您已经拥有'id'属性,因此可以通过id找到DOM元素:)

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