使用 jQuery 将类添加到每个表行的第一个 TD
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3925509/
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
Using jQuery to add class to first TD on each table row
提问by Robert E
I have a table I'm working with that is like such:
我有一张正在使用的表,如下所示:
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tablecontent">
<tr class="tablerow">
<td>This is the td I want to add a class to.</td>
<td class="cell2">Stuff</td>
<td class="cell3">Stuff</td>
</tr>
<tr class="tablerow">
<td>This is the td I want to add a class to.</td>
<td class="cell2">Stuff</td>
<td class="cell3">Stuff</td>
</tr>
</table>
The first TD tag in each row does not have a class or ID to work with. I don't have access to change the HTML output so I figured to add in a bit of jQuery to target the first TD tag of each tablerow. How would I do this?
每行中的第一个 TD 标记没有要使用的类或 ID。我无权更改 HTML 输出,因此我想添加一些 jQuery 来定位每个 tablerow 的第一个 TD 标记。我该怎么做?
回答by user113716
$('#tablecontent td:first-child').addClass('someClass');
This uses the first-child selectorto select all <td>
elements in the #tablecontent
table that are a first-child
of their parent.
这使用第一个子选择器来选择表中作为其父<td>
元素的所有元素。#tablecontent
first-child
Example:http://jsfiddle.net/duKKC/
回答by Scott
You can try the below jQuery
你可以试试下面的jQuery
$('.tablerow').each(function(index) {
$(this).children('td').first().addClass('class');
});
This will solve your problem :)
这将解决您的问题:)
回答by Dror
$(".tablerow").find("td:first-child").addClass('class');
回答by Jeff Siver
I believe the following would work:
我相信以下方法会起作用:
$('.tablerow td:first-child').addClass('class');
回答by Christian Tellnes
$('#tablecontent td:first-child').addClass("first-row");