我有几个tr的表。我发现使用jQuery解决第一个<tr>
分配class='alt'
,下一个<tr>
class='alt-2'
和第三行class='alt-3'
的位置。如果表有很多行我想要这个脚本重复。请问你知道一些jQuery的解决方案吗?
感谢
<table id="news">
<thead>
<tr>
<th>Date</th>
<th>Headline</th>
<th id="autor">Author</th>
<th>Topic</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4">2011</th>
</tr>
<tr>
<td>Apr 15</td>
<td>jQuery 1.6 Beta 1 Released</td>
<td>John Resig</td>
<td>Releases</td>
</tr>
<tr>
<td>Feb 24</td>
<td>jQuery Conference 2011: San Francisco Bay Area</td>
<td>Ralph Whitbeck</td>
<td>Conferences</td>
</tr>
<tr>
<td>Feb 7</td>
<td>New Releases, Videos & a Sneak Peek at the jQuery UI Grid</td>
<td>Addy Osmani</td>
<td>Plugins</td>
</tr>
</table>
答案 0 :(得分:2)
如果您想定位tr
中的所有thead
,请使用:nth-child
$('#news tr').addClass(function (idx) {
var rem = idx % 3;
return 'alt' + (rem == 0 ? '' :'-'+ (rem + 1))
})
演示:Fiddle
答案 1 :(得分:0)
var i = 1;
$("#news tbody tr").each(function () {
$(this).addClass('alt-' + i);
i++;
});
答案 2 :(得分:0)
如果您想要包含所有tr
:
$('#news tr').each(function(i, z){
$(this).addClass('alt' + (i == 0 ? '' : '-' + (i + 1)));
});
或者如果只想在tbody
$('#news tbody tr').each(function(i, z){
$(this).addClass('alt' + (i == 0 ? '' : '-' + (i + 1)));
});
答案 3 :(得分:0)
请试试这个,
$("#news tr").addClass(function (idx) {
if(idx != 1){
return (idx!= 0) ? "alt-" + idx : "alt";
}
});