如何在 jQuery 中找出each()的最后一个索引?

问题描述 投票:0回答:6

我有这样的东西...

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

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

} );

我需要知道最后一个元素的索引是什么,所以我可以这样做......

if ( index !== lastIndex ) {

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

} else {

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

}

大家有什么想法吗?

jquery loops indexing each
6个回答
97
投票
var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});

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

9
投票

记得缓存选择器

$("ul li")
,因为它并不便宜。

缓存长度本身是一种微观优化,但这是可选的。

var lis = $("ul li"),
    len = lis.length;

lis.each(function(i) {
    if (i === len - 1) {
        $(this).append(";");
    } else {
        $(this).append(",");
    }
});

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

    } );

4
投票

这是另一种方法:

$('ul li').each(function() {
    if ($(this).is(':last-child')) {
        // Your code here
    }
})

3
投票

使用 jQuery .last();

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

演示

© www.soinside.com 2019 - 2024. All rights reserved.