Maintain reference to this in jQuery
I'm converting a bunch of hyperlinks to make simpl开发者_Go百科e GET requests using jQuery. I want to maintain the reference to this within the Ajax call, do i need to be using bind/live/something else?
$(document).ready(function(){
$(".mylink").click(function(){
var url = $(this).attr('href');
$.get(url,function(data){
$(this).parent().html(data); // this is now out of scope
});
return false;
});
});
$(document).ready(function(){
$(".moderate").click(function(){
var $this = $(this);
var url = $this.attr('href');
$.get(url,function(data){
$this.parent().html(data);
});
return false;
});
});
That should work for you.
$(document).ready(function(){
$(".moderate").click(function(){
var url = $(this).attr('href');
var that = $(this);
$.get(url,function(data){
that.parent().html(data);
});
return false;
});
});
You need to save this to another variable, like this:
$(document).ready(function(){
$(".mylink").click(function(){
var realThis = this;
var url = $(this).attr('href');
$.get(url,function(data){
$(realThis).parent().html(data); // realThis is now in scope
});
return false;
});
});
The AJAX callback can access the variables of the outer method, so this technique works fine.
You only need to call live if you want to handle all .mylink elements, even ones that were added later.
Scoping is a mess in javascript :)
In jQuery 1.4, you have a built-in proxy function that can bring the scope into any callback, see: http://api.jquery.com/jQuery.proxy/.
But it's quite easy to create one yourself:
var proxy = function( fn, scope ) {
if ( typeof fn !== 'function' ) {
return function() {};
}
scope = scope || this;
return function() {
return fn.apply( scope, Array.prototype.slice.call(arguments) );
};
}
$(document).ready(function(){
$(".moderate").click(function(){
var url = $(this).attr('href');
$.get(url, proxy(function(data) {
$(this).parent().html(data);
}, this));
return false;
});
});
You can also put the scope in a variable and access it later:
$(document).ready(function(){
$(".moderate").click(function(){
var scope = this;
var url = $(this).attr('href');
$.get(url, function(data) {
$(scope).parent().html(data);
});
return false;
});
});
加载中,请稍侯......
精彩评论