Chr*_*ris 24 javascript ajax jquery scope
我有一个ajax调用doop.php.
function doop(){
var old = $(this).siblings('.old').html();
var new = $(this).siblings('.new').val();
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + old + '&after=' + new,
success: function(resp) {
if(resp == 1) {
$(this).siblings('.old').html(new);
}
}
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是$(this).siblings('.old').html(new);线路没有做它应该做的事情.
谢谢..所有有用的评论/答案都被投了票.
更新:似乎问题的一半是范围(感谢帮助我澄清的答案),但另一半是我试图以同步方式使用ajax.我创建了一个新帖子
Gui*_*ois 48
您应该使用http://api.jquery.com/jQuery.ajax/中的上下文设置
function doop(){
var old = $(this).siblings('.old').html();
var newValue = $(this).siblings('.new').val();
$.ajax({
url: 'doop.php',
type: 'POST',
context: this,
data: 'before=' + old + '&after=' + newValue,
success: function(resp) {
if(resp == 1) {
$(this).siblings('.old').html(newValue);
}
}
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
"这个"将转移到成功范围,并将按预期行事.
Cre*_*esh 26
首先new是保留字.您需要重命名该变量.
要回答您的问题,是的,您需要this在成功回调之外的变量中保存,并在成功处理程序代码中引用它:
var that = this;
$.ajax({
// ...
success: function(resp) {
if(resp == 1) {
$(that).siblings('.old').html($new);
}
}
})
Run Code Online (Sandbox Code Playgroud)
这称为闭包.
this绑定到应用执行函数的对象.这可能是一些AJAX响应对象,或全局对象(window),或其他东西(取决于的实现$.ajax.
在进入$ .ajax调用之前,是否需要将$(this)捕获到变量中,然后将其作为参数传递给$ .ajax调用?或者我是否需要将其传递给匿名成功函数?如果这将解决问题,我将在哪里将其传递给$ .ajax?
this在确定success函数之前,确实需要一种方法来捕获值.创建闭包是实现此目的的方法.您需要定义一个单独的变量(例如self):
function doop() {
var old = $(this).siblings('.old').html();
var new = $(this).siblings('.new').val();
var self = this;
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + old + '&after=' + new,
success: function(resp) {
if(resp == 1) {
$(self).siblings('.old').html(new);
}
}
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
该success函数将保留self调用时的值,并且应该按预期运行.