javascript 使用 jQuery 为表的第二列添加类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9018593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add class with jQuery for second columns of table
提问by Paul Attuck
<table>
<tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
<tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
<tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
<tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
<tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
</table>
table td {
background-color: green;
padding: 5px;
border: 1px solid blue;
}
.red {
background-color: red;
}
LIVE:http://jsfiddle.net/zCduV/1/
直播:http : //jsfiddle.net/zCduV/1/
How can i add class .red with jQuery for second column in this table (in this example this is there where in td is ccc)?
我如何为该表中的第二列添加带有 jQuery 的类 .red(在本例中,这是 td 中的 ccc)?
回答by Deadlykipper
This maybe?
这也许?
// selects both table header and table data cells from the second column of the table
$('table th:nth-child(2), table td:nth-child(2)').addClass('red');
回答by SeanNieuwoudt
By using the jQuery nth-child selector:
通过使用 jQuery nth-child 选择器:
$('td:nth-child(2)').addClass('red');
Reference: http://api.jquery.com/nth-child-selector/
回答by frm
$('td:nth-child(2)').addClass('red');
回答by Awais Qarni
Take a look at jQuery nth-child-selector. This is what you are looking for.
看看 jQuery nth-child-selector。这就是你要找的。
$('td:nth-child(2)').addClass('red');