How to get the current iteration of each() loop in jQuery?
$('#selectDropDowns select').each(fu开发者_开发知识库nction() {
// 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(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.net/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.
精彩评论