问题
I am wondering why $(this) does not work after a jQuery ajax call.
My code is like this.
$('.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;
});
Why doesnt the $(this) work in this case after ajax call? It would work if I use it before the ajax but no effect after.
回答1:
In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.
You need to capture the "outer" $(this) first:
$('.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;
});
来源:https://stackoverflow.com/questions/1392789/jquery-ajax-call-this-does-not-work-after-success