<分区>
标签 javascript jquery css
<分区>
我有这张表:
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
...
</tbody>
它还在继续…… 我想让医生准备好根据他们的职位添加奇数类甚至偶数类。结束这样的事情:
<tbody>
<tr class="odd">
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr class="even">
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr class="odd">
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr class="even">
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
...
</tbody>
实现这个的方法是什么?我是否必须计算我有多少张 table 并根据他们的位置添加类(class)?这对我来说听起来不安全/不正确。
最佳答案
看看 nth-child
伪选择器 (MDN link) .
如果您只想分配一些样式,请使用:
tr:nth-child(2n+1) { // odd rows }
tr:nth-child(2n) { // even rows }
编辑:
正如 David Thomas 所建议的那样,这将提高可读性:
tr:nth-child(odd) { // odd rows }
tr:nth-child(even) { // even rows }
关于javascript - jQuery/CSS : Assigning classes to a table depends on their order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852383/