$('#selectDropDowns select').each(function() {
// do usual stuff
// do extra stuff only if this is the 4th iteration
});
为了在第4次迭代中完成额外的工作,我该如何检测它?如何获取jQuery中每个()循环的当前迭代?
$('#selectDropDowns select').each(function() {
// do usual stuff
// do extra stuff only if this is the 4th iteration
});
为了在第4次迭代中完成额外的工作,我该如何检测它?如何获取jQuery中每个()循环的当前迭代?
$('#selectDropDowns select').each(function(i) {
// do usual stuff
if (i==3)
{
// do extra stuff only if this is the 4th iteration
}
});
这是第5次迭代。基于零指数。 – epascarello
@epascarello:确定...已修复。 – yankee
像这样:
$('#selectDropDowns select').each(function(index, element) {
// index represents the current index of the iteration
// and element the current item of the array
});
$('#selectDropDowns select').each(function(index) {
// do usual stuff
if(index ==3){
// do extra stuff only if this is the 4th iteration
}
});
为什么这么“复杂”? –
@Felix King不知道你可以通过索引,只是创建一个小提琴很好地工作。这就是为什么我喜欢这个网站,我每天都会学到新东西 –
这是第5次迭代。基于零指数。 – epascarello
传递给each(..)
可以取两个参数的函数 - 索引和元素。这就是你看到的第一件事,当你打开文件:
.each(function(index, Element))
所以:
$('#selectDropDowns select').each(function(i) {
if (i == 3) ...
});
这是第5次迭代。基于零指数。 – epascarello
当然,更正 – Bozho
使用$(这)...
$('#selectDropDowns select').each(function(i, val) {
//Zero-index based thus to grab 4th iterator -> index = 3
if (i == 3) {
alert($(this).attr('id'));
}
}
请注意,你也可以在.each函数声明中获取索引和元素的值。
这是第5次迭代。基于零指数。 – epascarello
如果您不需要循环使用,则可以使用eq()。
$('#selectDropDowns select').eq(3);
看看文档:http://api.jquery.com/each/ –