我已经为问题创建了这个小提琴,因为您将看到有三个表使用 jQuery 的斑马条。
表 1 以正确的形式显示,因为它从 0 开始 tr 索引为偶数。表 2 从上一个表继续,它显示第一行为白色而不是深色。我认为它正在发生,因为它从上一个表的 tr 索引继续。
.HTML:
<table>
<caption> Table 1</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
<table>
<caption> Table 2</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
<table>
<caption> Table 3</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
JavaScript:
$('table').find('tr:even').css('background','#d0d0d0');
小提琴:http://jsfiddle.net/daljir/gryh5/
您可以使用find()
分别"处理"每个表:
$("table").find("tr:even").css("background", "#d0d0d0");
演示:http://jsfiddle.net/gryh5/1/
您正在选择文档中的所有<tr>
元素,您可以使用nth-child
选择器选择文档中所有偶数编号的<tr>
。
$('table tr:nth-child(2n)').css('background','#d0d0d0');
http://jsfiddle.net/Kyle_Sevenoaks/gryh5/7/
这是因为您通常会选择所有 tr(无论表如何),并且当它们堆叠时,您将获得此特定行为。试试这个:
$('table').find('tr:even').css('background','#d0d0d0');
检查小提琴
这有效
<table id="t1">
<caption> Table 1</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
<table id="t2">
<caption> Table 2</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
<table id="t3">
<caption> Table 3</caption>
<tr>
<th>Table Head 1</th>
<td>Table Data 1</td>
</tr>
<tr>
<th>Table Head 2</th>
<td>Table Data 2</td>
</tr>
<tr>
<th>Table Head 3</th>
<td>Table Data 3</td>
</tr>
</table>
和JS:
$(function(){
$('#t1 tr:even, #t2 tr:even, #t3 tr:even').css('background','#d0d0d0');
});
JSFIDDLE: http://jsfiddle.net/SnakeEyes/gryh5/2/
> http://jsfiddle.net/gryh5/9/
$('table').each(function(){
$(this).find('tr').filter(':even').css('background','#d0d0d0');
});