为什么这个jquery和css在html表中不一致?

时间:2014-01-04 21:21:43

标签: jquery css jquery-selectors html-table

我有以下jquery代码和:

$("table.altRow > tbody > tr:odd").addClass("oddColor");
$("table.altRow > tbody > tr:even").addClass("evenColor");

以及以下css:

.altRow tbody tr.evenColor { background-color : #e9e9e9; }
.altRow tbody tr.oddColor { background-color : #ffffff; }

似乎会产生不一致的结果

有些桌子有" evenColor"在第一个身体TR和其他人的班级有" oddColor"作为一个类添加到第一个身体TR。

为什么这不能保持一致?我希望白色(#ffffff)行始终是第一个主体行backcolor

如果我在一个页面上有两个表格。一个将evenColor放在一行的第一行,另一个表的oddColor作为另一个表的第一行的类。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

这是因为jQuery的:odd and :even selectors适用于所有选定元素的列表,无论它们在上下文中的位置如何。

如果你想使用jQuery,请改用:nth-child(odd) and :nth-child(even),这样:

$(".altRow tbody tr:nth-child(odd)").addClass("oddColor");
$(".altRow tbody tr:nth-child(even)").addClass("evenColor");

表现提示

  1. 简化您的选择器,它们不需要那么长。如果您将课程altRow应用于<tbody>,则可以使用.altRow tr:nth-child(even)等选择器

  2. 仅使用CSS,不使用jQuery:

    .altRow tr { background-color : #e9e9e9; } 
    .altRow tr:nth-child(odd) { background-color : #ffffff; } 
    

    在IE8中,:nth-child仅支持使用Selectivizr或类似的库。

答案 1 :(得分:0)

:odd选择元素,而不是它们的父元素(如在其表中的第n个tr中),但是在DOM中作为一个整体。

如果您想要一个示例,请查看以下内容:http://jsfiddle.net/PGdMz/

如果您不明白,请阅读jQuery网站上的摘录:

In particular, note that the 0-based indexing means that, counter-intuitively, :odd selects the second element, fourth element, and so on within the matched set.

所以你应该做的是写下这个:

$("table.altRow > tbody > tr:nth-child(odd)").addClass("oddColor");
$("table.altRow > tbody > tr:nth-child(even)").addClass("evenColor");

如果我在示例中更新:

http://jsfiddle.net/PGdMz/1/