2011-09-09 43 views
0

我有以下的jQuery .each loopjQuery的。每个函数的问题

$('.table-data tbody tr td').each(function(index) { 

    $('.table-data tbody tr td' + ':nth-child(' + index + ')').addClass('nth-' + index); 


}); 

的问题是,它会工作,但.table-data tbody tr td'的最后一个元素不会得到一个类。为什么?

这是因为index是基于0吗?如何使其循环index + 1次?

+0

$(这)等于$(”表。 -data tbody tr td'+':nth-​​child('+ index +')') –

+0

@JapanPro - 是的,我花了一秒钟的时间才开始工作 - for循环。 – Iladarsda

回答

2

您不需要使用索引深入到当前元素,它比这更容易!

$(".table-data tbody td").each(function(index){ 
    $(this).addClass("nth-" + index); 
}); 

要重新编号内每一行的TD元素,试试这个。

$(".table-data tbody tr").each(function(index){ 
    $(this).find("td").each(function(index){ 
     $(this).addClass("nth-" + index); 
    }); 
}); 

,或者,如果你想成为一个有点聪明,这...

$(".table-data tbody td").each(function(){ 
    $(this).addClass("n-" + $(this).index()); 
}); 

在操作中查看:http://jsbin.com/usaqix

+0

'$(this).addClass(“nth-”+ ++ index);'在我的例子中是完美的!非常聪明!谢谢! – Iladarsda

+0

如何让它从每一行的'0开始计数?我必须把它放在双'.each'吗? – Iladarsda

+1

是的,我就是这么做的(见编辑)。 – centralscru

0

第n个孩子从1开始,所以是的,你的基于零的索引将无法正确工作。您需要在使用索引变量的地方执行索引+1,但它会迭代正确的次数。