2012-08-09 94 views
0

可能重复:
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)但它不起作用,可能是因为它在另一个功能里面。

非常感谢。在AJAX调用之前变量

+0

argh ..没有看到它的建议..我可以'关闭它,现在有人回答了 – eric01 2012-08-09 22:29:36

+1

只是标记了我自己。谢谢你让我知道。问候 – eric01 2012-08-09 22:32:04

回答

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 
    }); 
}); 
+2

第一个例子很整洁!我没有意识到功能!非常感谢。 – OptimusCrime 2012-08-10 00:08:05

1

搭上:

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

    var $this = $(this); 

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

      alert($this); 

     } 
    }) 
}); 
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); 
     } 
    }) 
}); 
+1

哦,不使用'var'?不是一个好主意。 – kapa 2012-08-10 00:12:39

+1

@bažmegakapa:vups,忘记了。谢谢你提醒我。 – OptimusCrime 2012-08-10 00:57:01