如何选择具有特定 id 的表中“sortasc”类的所有 <th> 个元素?
-
01-07-2019 - |
题
假设我有以下 HTML:
<table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
我知道我可以执行以下操作来获取所有 th 具有 class="sortasc" 的元素
$$('th.sortasc').each()
然而这给了我 th 两个表中的元素 富 和桌子 酒吧.
我怎样才能告诉它只给我表中的第 th 个元素 富?
解决方案
表#foo th.sortasc
其他提示
这是使用直接 JS 的方式:
var table = document.getElementById('tableId');
var headers = table.getElementsByTagName('th');
var headersIWant = [];
for (var i = 0; i < headers.length; i++) {
if ((' ' + headers[i].className + ' ').indexOf(' sortasc ') >= 0) {
headersIWant.push(headers[i]);
}
}
return headersIWant;
CSS 选择器类似于“#foo th.sortasc”。在 jQuery 中,这将是 $('#foo th.sortasc')。
使用嵌套表,例如:
<table id="foo">
<th class="sortasc">Header</th>
<tr><td>
<table id="nestedFoo">
<th class="sortasc">Nested Header</th>
</table>
</td></tr>
</table>
$('table#foo th.sortasc') 会给你 全部 这是因为你正在使用 后代选择器. 。如果你只想要 foo 的 th,那么你应该使用 子选择器 - $('table#foo > th.sortasc').
请注意,子选择器是 不支持 在 IE6 的 CSS 中,尽管 JQuery 仍然可以从 JavaScript 正确地执行此操作。
不隶属于 StackOverflow