在每个循环中检测是否存在下一个

时间:2013-02-03 11:41:13

标签: jquery

我会尝试让代码在这里说明一下:如果我可以使用条件来检查当前代码之后是否会有另一个迭代?

$('#%id% td').each(function(){ 
if(??????????){                       // if there will be a next iteration
while($(this).height() == thisheight){
    // do something here on this iteration, but only if there will be another.
}  
}
});

1 个答案:

答案 0 :(得分:2)

由于您似乎想要处理除最后一个元素之外的所有元素,因此您只需使用.slice [docs]删除集合中的最后一个元素:

$('#%id% td').slice(0, -1).each(function() {
    // no need for `if` statement here
    // ...
});

原始问题的答案是将当前迭代与元素数量进行比较:

var $elements = $('#%id% td');
var max = $elements.length - 1;

$elements.each(function(index) { 
    if (index < max) {
        // ...
    }
    // ...
});