简体   繁体   English

我如何选择全部 <th> 具有特定ID的表中“sortasc”类的元素?

[英]How do I select all <th> elements of class “sortasc” within a table with a specific id?

Let's say I have the following HTML: 假设我有以下HTML:

<table id="foo">
  <th class="sortasc">Header</th>
</table>

<table id="bar">
  <th class="sortasc">Header</th>
</table>

I know that I can do the following to get all of the th elements that have class="sortasc" 我知道我能做到下面让所有有类=“sortasc”的要素

$$('th.sortasc').each()

However that gives me the th elements from both table foo and table bar . 然而,这给了我表foo和表格th元素。

How can I tell it to give me just the th elements from table foo ? 我怎么能告诉它只给我表foo中的元素?

table#foo th.sortasc

This is how you'd do it with straight-up JS: 这就是你用直接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;

The CSS selector would be something like '#foo th.sortasc'. CSS选择器就像'#foo th.sortasc'。 In jQuery that would be $('#foo th.sortasc'). 在jQuery中将是$('#foo th.sortasc')。

With a nested table, like: 使用嵌套表,如:

<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') will give you all the th's because you're using a descendant selector . $('table#foo th.sortasc')会给你所有的东西,因为你正在使用一个后代选择器 If you only want foo's th's, then you should use the child selector - $('table#foo > th.sortasc'). 如果你只想要foo,那么你应该使用子选择器 - $('table#foo> th.sortasc')。

Note that the child selector is not supported in CSS for IE6, though JQuery will still correctly do it from JavaScript. 请注意,IE6中的CSS 不支持子选择器,尽管JQuery仍然可以通过JavaScript正确地执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM