我意识到下面的代码不是抓取元素的最有效方法,但是为了举例...
$('.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?
});
});
答案 0 :(得分: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.
});
});
答案 1 :(得分: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
});
});
答案 2 :(得分:3)
将它存储在每个内部的var之前。
$('.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?
});
});
答案 3 :(得分:1)
$('.myFirstClass').each(function(i){
var me = this;
$(this).find('.mySecondClass').each(function(j){
alert($(me).attr('id'));
});
});
这应该有效。