开发者

How to get the current iteration of each() loop in jQuery?

开发者 https://www.devze.com 2023-03-18 06:34 出处:网络
$(\'#selectDropDowns select\').each(fu开发者_开发知识库nction() { // do usual stuff // do extra stuff only if this is the 4th iteration
        $('#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.

0

精彩评论

暂无评论...
验证码 换一张
取 消