jQuery - 如何选择包含 th 的 tr?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/530513/
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 - how to select a tr that contains th's?
提问by George Mauer
Title pretty much says it all.
Given a table like
标题几乎说明了一切。
给定一个表
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
</table>
How to select the row which contains the th headers and no other?
如何选择包含第 th 个标题而没有其他标题的行?
回答by cletus
Expression:
表达:
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
or even just:
甚至只是:
$(function() {
$("tr:not(:has(td))").hide();
});
Full example:
完整示例:
<html>
<head>
<title>Layout</title>
</head>
<body>
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<th>Header 3</th>
<th>Datum 2</td>
</tr>
</table>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function() {
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
});
</script>
</body>
</html>
回答by Steve Platz
If possible, it would be ideal to enclose your table header inside a <thead> element
如果可能,最好将表格标题包含在 <thead> 元素中
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
That way, selecting your table header would be as simple as:
这样,选择表格标题就很简单了:
$('thead');
Or selecting only the <tr>
或者只选择 <tr>
$('thead tr');
Your markup would then be more readable, and styling your table becomes easier, as you can more easily target elements in the header or body of your table.
然后,您的标记将更具可读性,并且您的表格样式也变得更容易,因为您可以更轻松地定位表格标题或正文中的元素。
回答by Vincent Robert
jQuery("tr:has(th)")
will select every tr
that contains at least oneth
将选择tr
包含至少一个的每一个th
kthxbye :)
kthxbye :)
回答by Rob
Use the :has
selector:
使用:has
选择器:
$('tr:has(th)').addClass('sample')
Probably won't work if you have a table with mixed th
and td
children though.
如果你有一张混合桌th
和td
儿童桌,可能就行不通了。
回答by Chris KL
Dunno if it's like Dojo CSS3 queries, but you could use the first-child pseudo class, if jQuery supports it:
不知道它是否像 Dojo CSS3 查询,但你可以使用 first-child 伪类,如果 jQuery 支持它:
tr th:first-child
tr th:第一个孩子
or
或者
tr th:nth-child(1)
tr th:nth-child(1)
See: http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/
参见:http: //www.456bereastreet.com/archive/200601/css_3_selectors_explained/