假设我有以下的HTML:
<table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
我知道以下方法可以获取所有类为"sortasc"的元素。
$$('th.sortasc').each()
但是这会给我两个表格foo和bar中的th元素。
我该如何告诉它只给我来自表格foo的th元素?
假设我有以下的HTML:
<table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
$$('th.sortasc').each()
但是这会给我两个表格foo和bar中的th元素。
我该如何告诉它只给我来自表格foo的th元素?
table#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')会给你所有th,因为你正在使用后代选择器。如果你只想要foo的th,那么你应该使用子选择器 - $('table#foo>th.sortasc')。
请注意,子选择器在CSS中不受IE6支持,但是JQuery仍然可以从JavaScript中正确执行它(link3:not supported)。