在jQuery中,我如何从$.ajax回调函数访问$(this)
In jQuery, how can I access $(this) from an $.ajax callback function?
可能的重复项:
如何访问 $(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);
}
})
});
相关文章:
- 从AJAX回调函数中分离数据
- 如何从ajax成功回调函数中读取javascript变量
- 如何处理Ajax.BeginForm()OnError OnFailure回调
- 在AJAX中使用window.location.replace'成功'回调
- AJAX之前的Dojo回调
- 如何在ajax回调中使用类变量
- AJAX成功回调-执行javascript时出现问题
- 当使用命名函数作为jquery ajax成功回调时,我需要括号吗
- jQuery AJAX错误回调未运行
- 使用Javascript通过ajax回调更新DOM
- 在Ajax中难以在JavaScript中使用回调
- 在firefox中,使用jquery ajax不会调用错误和完整回调
- Backbone,Coffescript-在AJAX中将函数作为回调传递
- php执行后的Ajax回调
- AJAX 回调在 Firefox 中失败
- $.mobile.changePage 之后的回调函数通过 AJAX 加载
- 从类方法中的 ajax post 函数回调函数更改 javascript 类属性
- 需要Javascript回调ajax解释
- web服务正在调用错误回调(ajax)
- 选择initselection回调ajax -不加载默认值