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

In jQuery, how can I access $(this) from an $.ajax callback function?

本文关键字:回调 ajax 函数 this 访问 jQuery      更新时间:2023-09-26

可能的重复项:
如何访问 $(this) 内部 ajax 成功回调函数

我有这样的代码:

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

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

提前非常感谢。

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

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

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

像这样:

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

ajax 调用之前在变量中捕获以下内容:

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