javascript - How to get the current iteration of each() loop in jQuery? - Stack Overflow

$('#selectDropDowns select').each(function() { do usual stuff do extra stuff only if this

        $('#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
Add a ment  | 

6 Answers 6

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745325089a4622617.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信