使用jQuery在嵌套表结构中选择最高级别的td

时间:2014-03-28 15:24:47

标签: jquery dom jquery-selectors

我试图在这样的嵌套表结构中选择最高级别的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>

要轻松选择所需的tdtable > 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。谢谢!

2 个答案:

答案 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