我有一张这样的表:
<table>
<tr>
<th>h1</th>
<th>h2</th>
<th>h3</th>
</tr>
<tr>
some content here
</tr>
<tr>
<td>1</td> <td>2</td> <td>3</td>
</tr>
<tr>
inside this row, I have a table which contains 2 rows
</tr>
<tr>
<td>1</td> <td>2</td> <td>3</td>
</tr>
<tr>
inside this row, I have a table which contains 2 rows
</tr>
<tr>
<td>1</td> <td>2</td> <td>3</td>
</tr>
<tr>
inside this row, I have a table which contains 2 rows
</tr>
//it repeats like this
</table>
我想从第3行开始使用jquery为每3行应用替代颜色,即,我希望以下代码部分具有替代颜色。我该怎么办?感谢
<tr>
<td>1</td> <td>2</td> <td>3</td>
</tr>
<tr>
inside this row, I have a table which contains 2 rows
</tr>
基本上,我不希望选择标题行和标题行之后的第一行。之后,我想每次选择3行,并给它一个替代颜色。 3行将是上面显示的行。
答案 0 :(得分:2)
使用第n个子选择器
$("table tr:nth-child(3n)")
答案 1 :(得分:1)
$('table tr:nth-child(3n) td').css('background-color', 'red');
$('table tr:nth-child(3n+1) td').css('background-color', 'blue');
$('table tr:nth-child(3n+2) td').css('background-color', 'green');
答案 2 :(得分:0)
var totalOfRows = $('table').find('tr').length;
var rows = $('table').find('tr');
for(var i=0; i<totalOfRows;i++){
$(rows[i]).attr('bgcolor','red'); //logical here
}
for example, yo can write .css('background-color', 'blue'); .css('background-color', 'pink'); etc
答案 3 :(得分:0)
你可以使用纯css3
table tr:nth-child(3n+3) { background:red; }
或通过jquery,例如kmd97回答
$("table tr:nth-child(3n+3)").css("background","red");
3n表示每3个元素,+ 3表示从第3个元素开始。
你可以尝试这个online css tester