如何选择具有特定id的表格中所有class为"sortasc"的<th>元素?

4

假设我有以下的HTML:

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

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

我知道以下方法可以获取所有类为"sortasc"的元素。
$$('th.sortasc').each()

但是这会给我两个表格foobar中的th元素。

我该如何告诉它只给我来自表格footh元素?

4个回答

8

table#foo th.sortasc


Crud。我觉得它很容易,但我没想到它会那么容易。 - Mark Biek

3

以下是使用纯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;

0

CSS选择器会类似于'#foo th.sortasc'。在jQuery中,它将是$('#foo th.sortasc')。


0

使用嵌套表格,例如:

<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')会给你所有th,因为你正在使用后代选择器。如果你只想要foo的th,那么你应该使用子选择器 - $('table#foo>th.sortasc')。

请注意,子选择器在CSS中不受IE6支持,但是JQuery仍然可以从JavaScript中正确执行它(link3:not supported)


还要注意,如果您的th元素位于thead或tbody或tfoot中,则此方法将失败。您需要使用$$('table#foo > th.sortasc, table#foo > thead th.sortasc, table#foo > tbody th.sortasc, table#foo > tfoot th.sortasc'),这有点不方便... - eyelidlessness

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接