2014-01-20 27 views
-1

如果我寫:jquery中的關鍵字'this'當函數內部時,如何改變範圍?

$('.myDiv').live('click',function(){ 
    $(this).find('.mySubDiv').each(function() { 
     $(this).hide(); 
    }); 
}); 

我想第二「這個」點.myDiv而不是.mySubDiv

有一些方法,其中我寫$(this.parent)或類似的東西,不保存$('.myDiv')在一個變量裏面?

+0

在您當前的代碼中,您需要哪些.each代碼?或者你在每個方面做得更多 –

回答

0

我經常這樣做:

var el = $(this); 

,然後只用el

0

this變化範圍取決於你在(它與迭代這樣做是因爲沿或觸發事件的jQuery也該代碼塊取決於稱爲每個功能的範圍來分配範圍)。但是,你可以將其保存爲一個變量「緩存」參考:

$('.myDiv').live('click',function(){ 
    var myDiv = $(this); // one example of caching `this` 

    $(this).find('.mySubDiv').each(function() { 
     var mySubDiv = $(this); // another example of caching `this` 

     $(this).hide(); 
    }); 
}); 

所以,現在你必須基於這樣$(this)被引用的.myDiv.mySubDiv具體實例的引用。