jQuery 选择第一个和第二个 td
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6588265/
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
jQuery Select first and second td
提问by stef
How can I add a class to the first and second td in each tr?
如何在每个 tr 的第一个和第二个 td 中添加一个类?
<div class='location'>
<table>
<tbody>
<tr>
<td>THIS ONE</td>
<td>THIS ONE</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>THIS ONE</td>
<td>THIS ONE</td>
<td>else</td>
<td>here</td>
</tr>
</tbody>
</table>
</div>
For the first td, this does nothing?
对于第一个 td,这没有任何作用?
$(".location table tbody tr td:first-child").addClass("black");
Can I also use second-child?
我也可以用二胎吗?
回答by James Montagne
$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");
回答by Felix Kling
To select the first and the second cell in each row, you could do this:
要选择每行中的第一个和第二个单元格,您可以执行以下操作:
$(".location table tbody tr").each(function() {
$(this).children('td').slice(0, 2).addClass("black");
});
回答by Deepak Lamichhane
You can do in this way also
你也可以这样做
var prop = $('.someProperty').closest('tr');
If the number of tr is in array
如果 tr 的数量在数组中
$.each(prop , function() {
var gotTD = $(this).find('td:eq(1)');
});
回答by Mark Coleman
If you want to add a class to the first andsecond td you can use .each()
and slice()
如果你想在第一个和第二个 td添加一个类,你可以使用.each()
和slice()
$(".location table tbody tr").each(function(){
$(this).find("td").slice(0, 2).addClass("black");
});
回答by thecodeparadox
$(".location table tbody tr").each(function(){
$('td:first', this).addClass('black').next().addClass('black');
});
another:
其他:
$(".location table tbody tr").find('td:first, td:nth-child(2)').addClass('black');
回答by Yash
jquery provides one more function: eq
jquery 提供了另外一个函数:eq
Select first tr
选择第一个 tr
$(".bootgrid-table tr").eq(0).addClass("black");
$(".bootgrid-table tr").eq(0).addClass("black");
Select second tr
选择第二个tr
$(".bootgrid-table tr").eq(1).addClass("black");
$(".bootgrid-table tr").eq(1).addClass("black");
回答by Steeven
You can just pick the next td:
您可以选择下一个 td:
$(".location table tbody tr td:first-child").next("td").addClass("black");