2009-07-30 32 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')); 
    }); 
}); 

这应该工作。

相关问题