似乎我无法在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();
}
});
答案 0 :(得分:54)
$(this)
应该是什么?如果您在该函数之外引用它,则可以将其存储到变量中。
$('#someLink').click(function() {
var $t = $(this);
$.ajax( ... , function() {
$t.parent().remove();
});
}
答案 1 :(得分:53)
查看上下文选项 - 对我来说非常适合:
$.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!
}
});
答案 2 :(得分:5)
如果您希望在ajax调用的上下文中this
为this
,您还可以使用.bind()
,如下所示:
$.ajax({
url: 'some_url'
success: function(data) {
// do something 'this'
}.bind(this)
})
它将成功回调中this
的值绑定到外部的this
。
答案 3 :(得分:4)
尝试调用$.proxy
,更改函数内的this
范围:
$.ajax({
success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});
答案 4 :(得分:0)
我看不到$(this)
引用任何内容,但更简单的方法是为元素提供类或id以及来自jquery的引用:
而不是:
$(this).parent().remove();
你可以这样做:
$('#element_id').parent().remove();
注意:这里我假设您正在处理一个元素/迭代。