Jquery AJAX调用:$(此)在成功后不起作用
我想知道为什么$(这个)在jQueryAjax调用后不起作用 我的代码是这样的Jquery AJAX调用:$(此)在成功后不起作用,jquery,ajax,this,Jquery,Ajax,This,我想知道为什么$(这个)在jQueryAjax调用后不起作用 我的代码是这样的 $('.agree').live("click", function(){ // use live for binding of ajax results var id=($(this).attr('comment_id')); $.ajax({ type: "POST", url: "includes/ajax.php?request=agree&i
$('.agree').live("click", function(){ // use live for binding of ajax results
var id=($(this).attr('comment_id'));
$.ajax({
type: "POST",
url: "includes/ajax.php?request=agree&id="+id,
success: function(response) {
$(this).append('hihi');
}
});
return false;
});
在这种情况下,为什么在ajax调用之后$(this)不起作用?如果我在ajax之前使用它,它会起作用,但在ajax之后不会起作用。在jQuery ajax回调中,“this”是对ajax请求中使用的选项的引用。它不是对DOM元素的引用 您需要先捕获“外部”$(此):
$('.agree').live("click", function(){ // use live for binding of ajax results
var id=($(this).attr('comment_id'));
var $this = $(this);
$.ajax({
type: "POST",
url: "includes/ajax.php?request=agree&id="+id,
success: function(response) {
$this.append('hihi');
}
});
return false;
});
我建议您阅读一下JavaScript函数范围,以及Doug Crockford对该语言的理解,还有一件事。我可以穿越它吗?像最近的$this.closest('div').html('hihi');是的,您的新
$this
变量包含一个jquery对象,因此您可以像对待$(this)
一样对待它,这对我也很有帮助