2010-01-19 37 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