jQuery 如何找出jQuery中each()的最后一个索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6061863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Find Out Last Index of each() in jQuery?
提问by daGrevis
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?
有什么想法吗,伙计们?
回答by Luke Sneeringer
var total = $('ul li').length;
$('ul li').each(function(index) {
if (index === total - 1) {
// this is the last one
}
});
回答by BnW
var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
回答by Raynos
Remember to cache the selector $("ul li")
because it's not cheap.
请记住缓存选择器,$("ul li")
因为它并不便宜。
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(",");
}
});
回答by Mutt
var length = $( 'ul li' ).length
$( 'ul li' ).each( function( index ) {
if(index !== (length -1 ))
$( this ).append( ',' );
else
$( this ).append( ';' );
} );
回答by Marco Allori
回答by Luca Fagioli
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
}
})