在表td上添加多个类 [英] Adding multiple classes on table td

查看:139
本文介绍了在表td上添加多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dynamic table that needs to assign each TD it's own class. In the example below, .one is being applied to all TDs for this table. Using just CSS (or Jquery), can I assign td classes .two and .three to the second and third children of this table?

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

动态 - 要说明,表格中的TD / TR数量未知。因此,CSS必须足够聪明才能调整,无论是否有3个TD / TR或10个TD / TR。

Dynamic - To clarify, the numbers of TDs/TRs in the table are unknown. Therefore, the CSS has to be smart enough to adjust regardless if there are 3 TDs/TRs or 10 TDs/TRs.

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/

See JS Fiddle here: http://jsfiddle.net/bigthyme/kM7H9/

推荐答案

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

You can use each elements index among the set as a lookup:

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

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


$ b b

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

你不需要这样做;您可以不使用类来定位它们:

You don't need to do this though; you can target them without using a class:

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/

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

Which has pretty good support in modern browsers. This does require you to explicitly set the colors for each row, and thus know how many rows you'll have. If you don't know how many rows you'll have you can use a more complicated selector:

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/

这篇关于在表td上添加多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆