2010-01-19 67 views
0

我正在转换一堆超链接来使用jQuery进行简单的GET请求。我想在Ajax调用中保留对this的引用,是否需要使用bind/live /其他?在jQuery中维护对此的引用

$(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; 
    }); 
}); 

回答

3
$(document).ready(function(){ 
    $(".moderate").click(function(){ 
     var $this = $(this); 
     var url = $this.attr('href'); 

     $.get(url,function(data){ 
      $this.parent().html(data); 
     }); 
     return false; 
    }); 
}); 

这应该为你工作。

1
$(document).ready(function(){ 
    $(".moderate").click(function(){ 
     var url = $(this).attr('href'); 
     var that = $(this); 
     $.get(url,function(data){ 
      that.parent().html(data); 
     }); 
     return false; 
    }); 
}); 
+0

注意,'this'(因此'那')是一个DOM节点,'parent()'是一个jQuery函数。你需要做'$(that).parent()' – 2010-01-19 12:42:10

+0

需要分配'$(this)'而不是'this',否则你不能在它上面调用'parent()',因为它赢了不是一个jQuery对象。 – 2010-01-19 12:43:46

+0

我已经纠正它之前,你写你评论家伙! :) – kjagiello 2010-01-19 13:23:36

1

您需要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; 
    }); 
}); 

Ajax回调可以访问外部方法的变量,所以这种技术能正常工作。

你只需要调用live如果你想处理所有.mylink元素,甚至是后来添加的。

1

作用域是在JavaScript :)

在jQuery的1.4一塌糊涂,你有一个内置的代理功能,可以把范围到任何回调,请参阅:http://api.jquery.com/jQuery.proxy/

但它很容易地创建一个自己:

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; 
    }); 
}); 

你也可以把范围在变量中,稍后访问它:

$(document).ready(function(){ 
    $(".moderate").click(function(){ 
     var scope = this; 
     var url = $(this).attr('href'); 
     $.get(url, function(data) { 
      $(scope).parent().html(data); 
     }); 
     return false; 
    }); 
}); 
+0

在Javascript中对范围的一般理解是一团糟,而不是JavaScript范围本身:) – 2010-01-19 12:45:18