[英]jquery each loop in a each loop
我有一些用作容器的div,我想遍歷它們,然后遍歷其中的項目。
所以不是$('.stackContainer .stackItem').each(
而是這樣的:
// setup stacks
$('.stackContainer').each(function(containerIndex) {
//console.log($(this));
console.log(containerIndex);
$(this).('.stackItem').each(function(itemIndex) {
console.log(itemIndex);
}
});
只有這樣工作。 這怎么可能?
嘗試
$('.stackContainer').each(function(containerIndex) {
//console.log($(this));
console.log(containerIndex);
$(this).find('.stackItem').each(function(itemIndex) {
console.log(itemIndex);
}
});
嘗試find()
方法:
$('.stackContainer').each(function(containerIndex) {
//console.log($(this));
console.log(containerIndex);
$(this).find('.stackItem').each(function(itemIndex) {
console.log(itemIndex);
}
});
正如其他答案所指出的,這樣做的方法很多。 這是一種解決方案: 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
變量每次開機父容器時間重置為零。
從側面講,出於性能原因,如果集合的大小可能是任意的,則應避免使用jQuery的each():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.