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

爱⌒轻易说出口 提交于 2019-12-18 10:38:12

问题


I have something like this...

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

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

} );

I need to know what index will be for last element, so I can do like this...

if ( index !== lastIndex ) {

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

} else {

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

}

Any ideas, guys?


回答1:


var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});



回答2:


var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});



回答3:


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(",");
    }
});



回答4:


    var length = $( 'ul li' ).length
    $( 'ul li' ).each( function( index ) {
        if(index !== (length -1 ))
          $( this ).append( ',' );
        else
          $( this ).append( ';' );

    } );



回答5:


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
    }
})



回答6:


using jQuery .last();

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

DEMO



来源:https://stackoverflow.com/questions/6061863/how-to-find-out-last-index-of-each-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!