jQuery 如何访问ajax成功回调函数中的$(this)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2643798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to access the $(this) inside ajax success callback function
提问by Yalamber
It seems that i cannot access $(this) inside jquery ajax success function. please see below code.
似乎我无法在 jquery ajax 成功函数中访问 $(this) 。请看下面的代码。
$.ajax({
type: 'post',
url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
data: 'action='+$action+'&user_id='+$user_id,
success: function(response){
//cannot access $(this) here $(this).parent().remove();
}
});
回答by nickf
What should $(this)
be? If you have a reference to it outside that function, you can just store it into a variable.
应该$(this)
是什么?如果您在该函数之外有对它的引用,则可以将其存储到变量中。
$('#someLink').click(function() {
var $t = $(this);
$.ajax( ... , function() {
$t.parent().remove();
});
}
回答by Enigma Plus
Check out the context option - works perfectly for me:
查看上下文选项 - 非常适合我:
$.ajax({
context: this,
type: 'post',
url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
data: 'action='+$action+'&user_id='+$user_id,
success: function(response){
//can access this now!
}
});
回答by Sung Cho
If you want this
to be this
in the context of your ajax call, you can also use .bind()
like the following:
如果你想this
成为this
你的Ajax调用的情况下,也可以使用.bind()
像下面这样:
$.ajax({
url: 'some_url'
success: function(data) {
// do something 'this'
}.bind(this)
})
It binds the value of this
inside the success callback to this
outside.
它将this
成功回调内部的值绑定到this
外部。
回答by Jan Jongboom
回答by Sarfraz
I can't see $(this)
referencing anything but easier way would be to give the element a class or id and reference that from jquery:
我看不到$(this)
引用任何东西,但更简单的方法是给元素一个类或 id 并从 jquery 引用它:
Instead of:
代替:
$(this).parent().remove();
You could do:
你可以这样做:
$('#element_id').parent().remove();
Note:Here I assume that you are dealing with one element/iteration.
注意:这里我假设您正在处理一个元素/迭代。