2

我已经为问题创建了这个小提琴,因为您将看到三个使用 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/

4

5 回答 5

5

您可以find()分别“使用”每个表:

$("table").find("tr:even").css("background", "#d0d0d0");

演示:http: //jsfiddle.net/gryh5/1/

于 2012-09-26T08:07:20.803 回答
4

您正在选择<tr>文档中的所有元素,您可以使用nth-childto 选择器来选择文档中的所有偶数<tr>

$('table tr:nth-child(2n)').css('background','#d0d0d0');

http://jsfiddle.net/Kyle_Sevenoaks/gryh5/7/

于 2012-09-26T08:10:22.157 回答
1

这是因为您通常选择所有 tr(与表格无关),并且当它们堆叠时您会得到这种特殊行为。试试这个:

$('table').find('tr:even').css('background','#d0d0d0');

检查小提琴

于 2012-09-26T08:06:57.053 回答
0

这有效

<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/

于 2012-09-26T08:08:39.300 回答
0

http://jsfiddle.net/gryh5/9/

$('table').each(function(){
   $(this).find('tr').filter(':even').css('background','#d0d0d0');
});
于 2012-09-26T08:20:07.233 回答