可能重复:
如何在ajax成功回调函数中访问$(this)
我有这样的代码:
$('.each_button').click(function(){
$.ajax({ type: 'POST', url: process.php, data: data, success: function(data){
/////
}
})
});
Run Code Online (Sandbox Code Playgroud)
如何访问$('.each_button')触发事件的内容?我尝试$(this)但它不起作用,可能是因为它在另一个函数内部..
非常感谢提前.
小智 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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
或者$.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
});
});
Run Code Online (Sandbox Code Playgroud)
这些方法的一个好处是它可以让你重用这个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
});
});
Run Code Online (Sandbox Code Playgroud)