我试图在这样的嵌套表结构中选择最高级别的td
(在第一级td
内,有更多表td
s应该没有不被选中
<table>
<tr>
<td> <!-- this is what I want to select -->
<table /> <!-- more td's inside that I don't want to select -->
</td>
</tr>
<tr>
<td> <!-- this is what I want to select -->
<table /> <!-- more td's inside that I don't want to select -->
</td>
</tr>
</table>
要轻松选择所需的td
:table > tr > td
。但是table
标记可能tbody
:
<table>
<tbody>
<tr>
<td> <!-- this is what I want to select -->
<table /> <!-- more td's inside that I don't want to select -->
</td>
</tr>
<tr>
<td> <!-- this is what I want to select -->
<table /> <!-- more td's inside that I don't want to select -->
</td>
</tr>
</tbody>
</table>
这本身也很容易:table > tbody > tr > td
。
如何找到一个不依赖于>
子选择器并且普遍适用的简单表达式?
像table tr > td
之类的东西(显然它不起作用,因为它在嵌套表中选择td
。谢谢!
答案 0 :(得分:1)
正如我在评论中所表达的那样,我赞成table > tbody > tr > td
,但作为替代方案,您可以使用
td:not(td td)
这将选择不是td
元素后代的所有td
元素。但请注意,这将仅与jQuery一起使用,因为您通常无法将复杂的选择器与:not
一起使用。
或者,使用.not
方法:
$('td').not('td td')
答案 1 :(得分:0)
正确答案是:
$('#tbl1').find('tr:first').parent().children().not(':not(td)')
.not(':not(td)') 删除非 td 标签。
示例:
<table id="tbl1">
<tr>
<td>1</td>
<input type="hidden" name="hidden1" value="something">
<td>2</td>
<td>
<table>
<tr><td>1</td>
<input type="hidden" name="hidden1" value="something">
<td>2</td>
</tr>
</table>
</td>
</tr>
</table>
<table id="tbl2">
<tbody>
<tr>
<td>1</td>
<input type="hidden" name="hidden1" value="something">
<td>2</td>
<td>
<table>
<tr>
<td>1</td>
<input type="hidden" name="hidden1" value="something">
<td>2</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
代码:
var r1 = $('#tbl1').find('tr:first').children();
var r2 = $('#tbl1').find('tr:first').children().not(':not(td)');
var r3 = $('#tbl2').find('tr:first').children();
var r4 = $('#tbl2').find('tr:first').children().not(':not(td)');
console.log ("r1: ", r1.length);
console.log ("r2: ", r2.length);
console.log ("r3: ", r3.length);
console.log ("r4: ", r4.length);
输出:
"r1: ", 4
"r2: ", 3
"r3: ", 4
"r4: ", 3