Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在具有特定id的表中选择类“sortasc”的所有元素?_Javascript_Prototypejs - Fatal编程技术网

Javascript 如何在具有特定id的表中选择类“sortasc”的所有元素?

Javascript 如何在具有特定id的表中选择类“sortasc”的所有元素?,javascript,prototypejs,Javascript,Prototypejs,假设我有以下HTML: <table id="foo"> <th class="sortasc">Header</th> </table> <table id="bar"> <th class="sortasc">Header</th> </table> 然而,这给了我来自表foo和表bar的th元素 我怎么能告诉它只给我table foo中的th元素呢?tablefoo th.sorta

假设我有以下HTML:

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

<table id="bar">
  <th class="sortasc">Header</th>
</table>
然而,这给了我来自表foo和表bar的th元素


我怎么能告诉它只给我table foo中的th元素呢?

tablefoo th.sortasc

CSS选择器类似于“foo th.sortasc”。在jQuery中,这将是$'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;

使用嵌套表,如:

<table id="foo">
  <th class="sortasc">Header</th>
  <tr><td>
    <table id="nestedFoo">
      <th class="sortasc">Nested Header</th>
    </table>
  </td></tr>
</table>
$'tablefoo th.sortasc'将为您提供所有th,因为您正在使用。如果您只需要foo的th,那么应该使用-$'tablefoo>th.sortasc'


注意,子选择器在IE6的CSS中,尽管JQuery仍然可以从JavaScript正确地执行它。

Crud。我认为这很容易,但我不认为这是那么容易。还要注意,如果你的th元素在thead、tbody或tfoot中,这将失败。您需要$$'tablefoo>th.sortasc,tablefoo>thead th.sortasc,tablefoo>tbody th.sortasc,tablefoo>tfoot 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>