jQuery, .each function question
I have following jQuery .each loop
:
$('.table-data tbody tr td').each( function(index) {
$('.table-data tbody tr td' + ':nth-child(' + index + ')' ).addClass( 'nth-' + index );
});
The problem is that it will work, but the last element of the .table-data tbody开发者_JS百科 tr td'
will not get a class. Why?
Is this because index
is 0 based? How to make it loop for index
+ 1 time?
You don't need to drill down to the current element using the index, it's easier than that!
$(".table-data tbody td").each(function(index){
$(this).addClass("nth-" + index);
});
To renumber the TD elements within each row, try this.
$(".table-data tbody tr").each(function(index){
$(this).find("td").each(function(index){
$(this).addClass("nth-" + index);
});
});
OR, if you want to be a bit cleverer, this...
$(".table-data tbody td").each(function(){
$(this).addClass("n-" + $(this).index());
});
See this in action: http://jsbin.com/usaqix
The nth child starts on 1, so yes, your zero based index won't work correctly on it. You'll need to do index+1 where you use the index variable - but it will iterate the right number of times.
精彩评论