daG*_*vis 39 indexing each jquery loops
我有这样的事......
$( 'ul li' ).each( function( index ) {
$( this ).append( ',' );
} );
Run Code Online (Sandbox Code Playgroud)
我需要知道最后一个元素的索引是什么,所以我可以这样做......
if ( index !== lastIndex ) {
$( this ).append( ',' );
} else {
$( this ).append( ';' );
}
Run Code Online (Sandbox Code Playgroud)
伙计们,有什么想法?
Luk*_*ger 82
var total = $('ul li').length;
$('ul li').each(function(index) {
if (index === total - 1) {
// this is the last one
}
});
Run Code Online (Sandbox Code Playgroud)
BnW*_*BnW 14
var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Run Code Online (Sandbox Code Playgroud)
记得缓存选择器$("ul li")
因为它不便宜.
缓存长度本身是一个微优化,但这是可选的.
var lis = $("ul li"),
len = lis.length;
lis.each(function(i) {
if (i === len - 1) {
$(this).append(";");
} else {
$(this).append(",");
}
});
Run Code Online (Sandbox Code Playgroud)
var length = $( 'ul li' ).length
$( 'ul li' ).each( function( index ) {
if(index !== (length -1 ))
$( this ).append( ',' );
else
$( this ).append( ';' );
} );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
71441 次 |
最近记录: |