How to Find Out Last Index of each() in jQuery?

后端 未结 6 1800
轻奢々
轻奢々 2020-12-24 06:45

I have something like this...

$( \'ul li\' ).each( function( index ) {

  $( this ).append( \',\' );

} );

I need to know what index will b

相关标签:
6条回答
  • 2020-12-24 07:06

    using jQuery .last();

    $("a").each(function(i){
      if( $("a").last().index() == i)
        alert("finish");
    })
    

    DEMO

    0 讨论(0)
  • 2020-12-24 07:10
    var arr = $('.someClass');
    arr.each(function(index, item) {
    var is_last_item = (index == (arr.length - 1));
    });
    
    0 讨论(0)
  • 2020-12-24 07:14
    var total = $('ul li').length;
    $('ul li').each(function(index) {
        if (index === total - 1) {
            // this is the last one
        }
    });
    
    0 讨论(0)
  • 2020-12-24 07:20

    Remember to cache the selector $("ul li") because it's not cheap.

    Caching the length itself is a micro optimisation though, that's optional.

    var lis = $("ul li"),
        len = lis.length;
    
    lis.each(function(i) {
        if (i === len - 1) {
            $(this).append(";");
        } else {
            $(this).append(",");
        }
    });
    
    0 讨论(0)
  • 2020-12-24 07:27
        var length = $( 'ul li' ).length
        $( 'ul li' ).each( function( index ) {
            if(index !== (length -1 ))
              $( this ).append( ',' );
            else
              $( this ).append( ';' );
    
        } );
    
    0 讨论(0)
  • 2020-12-24 07:29

    It is a very old question, but there is a more elegant way to do that:

    $('ul li').each(function() {
        if ($(this).is(':last-child')) {
            // Your code here
        }
    })
    
    0 讨论(0)
提交回复
热议问题