在jQuery中,如何从$ .ajax回调函数中访问$(this)?

时间:2012-08-09 22:27:19

标签: javascript jquery

  

可能重复:
  how to access the $(this) inside ajax success callback function

我有这样的代码:

$('.each_button').click(function(){

$.ajax({ type: 'POST', url: process.php, data: data, success: function(data){

/////
       }
   })
});

如何访问触发事件的$('.each_button')?我试过$(this)但是它不起作用,可能是因为它在另一个函数内部。

提前多多感谢。

3 个答案:

答案 0 :(得分:5)

由于某种原因,每个人都想使用变量。这不是必要的。

$('.each_button').click(function(){

    $.ajax({
        context: this, // <-- do this instead...
        type: 'POST', 
        url: process.php, 
        data: data, 
        success: function(data) {
               // ...now 'this' is the element you want
            alert(this.className);
        }
    });

});

如果您愿意,可以使用$.proxy ...

$('.each_button').click(function(){

    $.ajax({
        type: 'POST', 
        url: process.php, 
        data: data, 
        success: $.proxy(function(data) {
               // ...now 'this' is the element you want
            alert(this.className);
        }, this) // <-- bind the context
    });

});

这些方法的一个好处是它允许您重用success函数...

function ajax_success(data) {
    alert(this.className);
}

$('.each_button').click(function(){
    $.ajax({
        context: this,
        type: 'POST', 
        url: process.php, 
        data: data, 
        success: ajax_success
    });
});

答案 1 :(得分:2)

您可以将对象保存在另一个变量中,并在function(data)

中访问它

这样的事情:

$('.each_button').click(function(){
    var $obj = $(this);
    $.ajax({
        type: 'POST', 
        url: process.php, 
        data: data, 
        success: function(data) {
            $obj.val(data.foobar);
        }
    })
});

答案 2 :(得分:1)

在ajax调用之前将其捕获到变量中:

$('.each_button').click(function(){

    var $this = $(this);

    $.ajax({ type: 'POST', url: process.php, data: data, success: function(data){

            alert($this);

       }
   })
});