1

我有一个动态表,需要为每个 TD 分配它自己的类。在下面的示例中,.one 应用于此表的所有 TD。仅使用 CSS(或 Jquery),我可以将 td 类 .two 和 .three 分配给该表的第二个和第三个孩子吗?

[请不要在TD中添加类名;这是动态表]

动态- 澄清一下,表中 TD/TR 的数量是未知的。因此,无论是 3 个 TD/TR 还是 10 个 TD/TR,CSS 都必须足够智能以进行调整。

HTML:

<table id="foo">
  <tr>
   <td>One</td>
  </tr>
  <tr>
   <td>Two</td>
  </tr>
  <tr>
   <td>Three</td>
  </tr>
</table>​

CSS:

 #foo{
   position: absolute;
   display: block;
   background: gray;
   color: white;
   height: 67px;
   width: 500px;
   border: 1px solid black;
}

tr {
   width: 500px;
   border: 1px solid black;
}

.one td {
   background: red;
   display: block;
   position: relative;
   left: 0px;
   width: 15px;
   border: 1px solid black;
   height: 19px;
   text-indent: 22px;
}

.two td {
   background: green;
   display: block;
   position: relative;
   left: 0px;
   width: 15px;
   border: 1px solid black;
   height: 19px;
   text-indent: 22px;
}

请参阅此处的 JS Fiddle:http: //jsfiddle.net/bigthyme/kM7H9/

4

1 回答 1

2

您可以使用集合中的每个元素索引作为查找:

​var classes = ['one', 'two', 'three'];

$("#foo td").attr("class", function (index, value) {
    return classes[index]; // 0 returns 'one', 1 returns 'two', etc.
});​​​​​​​​​​​​

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

不过,您不需要这样做;您可以在不使用类的情况下定位它们:

tr:nth-of-type(1) td { color: red }
tr:nth-of-type(2) td { color: green }
tr:nth-of-type(3) td { color: blue }​

演示:http: //jsfiddle.net/SzKbh/

在现代浏览器中有很好的支持。这确实需要您明确设置每行的颜色,从而知道您将拥有多少行。如果您不知道您将拥有多少行,您可以使用更复杂的选择器:

table tr:nth-child(2n+0) { color: red }
table tr:nth-child(2n+1) { color: blue }
table tr:nth-child(3n+0) { color: green }

演示:http: //jsfiddle.net/SzKbh/2/

于 2012-12-11T02:11:39.573 回答