【问题标题】:Adding multiple classes on table td在表 td 上添加多个类
【发布时间】:2012-11-28 13:11:56
【问题描述】:

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

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

动态 - 澄清一下,表中 TD/TR 的数量是未知的。因此,无论是 3 个 TDs/TR 还是 10 个 TDs/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/

【问题讨论】:

  • 什么是动态表?我只看到整个表都有“one”类。
  • 啊,是的,很抱歉含糊不清……请参阅新的编辑。
  • 您将有很多张桌子还是只有一张?如果您想在td 元素上使用.one,为什么要在桌面上?我很困惑。

标签: jquery html css html-table


【解决方案1】:

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

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

【讨论】:

  • 如果我想支持 IE8,有没有简单的方法可以做到这一点?不想使用像 selectivizr 这样的单独库(如果可能的话)。
  • @bigthyme 如果您想要完全支持,您可以在服务器端确定类,然后将已经提供的 HTML 发送出去。否则,您将需要使用库(无论是 jQuery 还是 jQuery + selectivizr)来为已有数年历史的浏览器提供支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 2021-03-21
  • 1970-01-01
相关资源
最近更新 更多