2012-06-10 124 views
0

我有一些div用作容器,我想循環它們,然後遍歷它中的項目。jquery每個循環中的每個循環

所以不$('.stackContainer .stackItem').each(,但這樣的事情:

// setup stacks 
$('.stackContainer').each(function(containerIndex) { 
    //console.log($(this)); 
    console.log(containerIndex); 

    $(this).('.stackItem').each(function(itemIndex) { 
     console.log(itemIndex);  
    } 
}); 

只有這樣的工作。 這可能怎麼樣?

+0

打開瀏覽器的開發者控制檯,你會知道爲什麼你的代碼是錯誤的。 –

回答

2

嘗試

$('.stackContainer').each(function(containerIndex) { 
    //console.log($(this)); 
    console.log(containerIndex); 

    $(this).find('.stackItem').each(function(itemIndex) { 
     console.log(itemIndex);  
    } 
}); 
1

嘗試find()方法:

$('.stackContainer').each(function(containerIndex) { 
    //console.log($(this)); 
    console.log(containerIndex); 

    $(this).find('.stackItem').each(function(itemIndex) { 
     console.log(itemIndex);  
    } 
}); 
0

許多這樣做的方法,如其他答案均表示。這裏有一個解決方案:http://jsfiddle.net/cezHH/3/

$(".stackContainer").each(function(stackIndex) { 
    $(this).children().css('class', '.stackItem').each(function(itemIndex) { 
     $(this).html($(this).html() + "=>" + itemIndex); 
    }); 
});​ 

或者,如果你想要做的是迭代所有在它們出現在頁面上的順序.stackItem的div,你實際上並不關心父母.stackContainer的div ,那麼你可以這樣做$('.stackItem').each(function(index) { ... });

嵌套遍歷.stackItem div的循環的原因是,如果您希望itemIndex變量在您每次切換父容器時重置爲零。