作用域是在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;
});
});
注意,'this'(因此'那')是一個DOM節點,'parent()'是一個jQuery函數。你需要做'$(that).parent()' – 2010-01-19 12:42:10
需要分配'$(this)'而不是'this',否則你不能在它上面調用'parent()',因爲它贏了不是一個jQuery對象。 – 2010-01-19 12:43:46
我已經糾正它之前,你寫你評論傢伙! :) – kjagiello 2010-01-19 13:23:36