2009-07-30 67 views
2

我知道下面的代碼是不斂元素的最有效的方式,但是對於一個例子的緣故...如何在jquery中訪問「THIS」的不同級別?

$('.myFirstClass').each(function(i){ 
    // Here is the first 'THIS' occurrence 
    $(this).find('.mySecondClass').each(function(j){ 
     // Here is the second 'THIS' occurrence 
     // How do i access the first occurrence from here? 
    }); 
}); 

回答

4

無需存儲變量。 jQuery的已經這樣做了第二個參數...

$(".myFirstClass").each(function(i, j){ 
    // I am represented as this or j 
    $(j).find(".mySecondClass").each(function(a, b){ 
    // I am represented as this or b 
    // I can communicate with j 
    }); 
}); 
3

商店此之前內每一個變種。

$('.myFirstClass').each(function(i){ 
    //store this 
    var $that = $(this); 
    $(this).find('.mySecondClass').each(function(j){ 
     //$that.something 
     // How do i access the first occurrence from here? 
    }); 
}); 
4

這樣的事情,

$('.myFirstClass').each(function(i){ 
    var firstClassThis = this; 
    $(this).find('.mySecondClass').each(function(j){ 
     // Here is the second 'THIS' occurrence 
     // How do i access the first occurrence from here? 
     //You can use firstClassThis here due to closure. 
    }); 
}); 
+0

`var firstClassThis = this;`是多餘的。 jQuery已經管理這些標識符。看到我的答案。 – Sampson 2009-07-30 16:49:37

+2

如果你已經在使用索引,你的代碼看起來更好。如果我不關心索引,我可能會在局部變量中捕獲「this」。 – SolutionYogi 2009-07-30 16:52:28

+0

確實如此。 +1 – Sampson 2009-07-30 19:08:01

1
$('.myFirstClass').each(function(i){ 
    var me = this; 
    $(this).find('.mySecondClass').each(function(j){ 
     alert($(me).attr('id')); 
    }); 
}); 

這應該工作。