I have been trying to use this inside an ajax function to refer the event target . but it seems that is not the way I think.
for example:
$('#test').live('click',function(){
$.ajax({
type:'post',
url:
data:...,
success:function(mes){开发者_StackOverflow中文版
$(this).append('mes');
}
});
});
so here $(this) does not refer to the ('#test') selector. what does it refer to?? thanks for any explanation.
Inside the success callback this
refers to a global object created by jQuery containing information about the AJAX rerquest. If you want to get the original DOM element you could capture it in a closure:
$('#test').live('click',function() {
var $this = $(this);
$.ajax({
type: 'post',
url: '/'
data: { },
success: function(mes) {
$this.append('mes');
}
});
});
or if you don't like closures you could pass it as a key/value pair of the request:
$('#test').live('click',function() {
$.ajax({
type: 'post',
url: '/'
data: { },
myElement: $(this),
success: function(mes) {
this.myElement.append('mes');
}
});
});
This could be useful in scenarios where the success
callback is not an anonymous function.
By default, this
will be the extended settings object used in the AJAX call. From the documentation:
By default, the context is an object that represents the ajax settings used in the call (
$.ajaxSettings
merged with the settings passed to$.ajax
).
You can use the context
setting to specify the object this
will refer to in callbacks:
$("#test").live("click", function() {
$.ajax({
type: "post",
context: this,
success: function(mes) {
// Here, this will refer to #test.
$(this).append('mes');
}
});
});
This is context. From JQuery site:
The this
reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
In that example, $(this)
would represent the $.ajax()
object.
精彩评论