admin管理员组文章数量:1420135
$('#selectDropDowns select').each(function() {
// do usual stuff
// do extra stuff only if this is the 4th iteration
});
In order to do the extra stuff on the 4th iteration, how can I detect it?
$('#selectDropDowns select').each(function() {
// do usual stuff
// do extra stuff only if this is the 4th iteration
});
In order to do the extra stuff on the 4th iteration, how can I detect it?
Share Improve this question asked Jul 9, 2011 at 15:41 SammySammy 311 silver badge2 bronze badges 1- 5 Have a look at the documentation: api.jquery./each – Felix Kling Commented Jul 9, 2011 at 15:43
6 Answers
Reset to default 4 $('#selectDropDowns select').each(function(i) {
// do usual stuff
if (i==3)
{
// do extra stuff only if this is the 4th iteration
}
});
The function you pass to each(..)
can take two arguments - the index and the element. This is the first thing you see when you open the documentation:
.each( function(index, Element) )
So:
$('#selectDropDowns select').each(function(i) {
if (i == 3) ...
});
Like this:
$('#selectDropDowns select').each(function(index, element) {
// index represents the current index of the iteration
// and element the current item of the array
});
If you do not need to loop through when you can use eq().
$('#selectDropDowns select').eq( 3 );
$('#selectDropDowns select').each(function(index) {
// do usual stuff
if(index ==3){
// do extra stuff only if this is the 4th iteration
}
});
Working example: http://jsfiddle/SgMuJ/1/
Use the $(this)...
$('#selectDropDowns select').each(function(i, val) {
//Zero-index based thus to grab 4th iterator -> index = 3
if (i == 3) {
alert($(this).attr('id'));
}
}
Note that you can also get the index and the value of the element in the .each function declaration.
本文标签: javascriptHow to get the current iteration of each() loop in jQueryStack Overflow
版权声明:本文标题:javascript - How to get the current iteration of each() loop in jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745325088a2653552.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论