【问题标题】:How to select table cells without selecting nested table cells in jQuery如何在 jQuery 中选择表格单元格而不选择嵌套表格单元格
【发布时间】:2010-10-20 23:02:35
【问题描述】:

我只想选择表格中的第一级“td”元素,而不是任何嵌套表格的单元格。 例如:

<table id="Outer">
    <tr>

        <td> --this one
        </td> 

        <td> --this one
            <table>
                <tr>
                    <td></td> -- but not this one or any deeper nested cells
                </tr>
            </table>
        </td>

    </tr> 
</table>

(是的,在产品代码中我会包括 tbody、thead...)

【问题讨论】:

    标签: jquery css-selectors sizzle


    【解决方案1】:

    我会使用children 选择器,它只选择与表达式匹配的直接子代。为了便于只选择外部表,我给它起了个名字。 注意:这不适用于您的示例,因为我已在 thead、tbody 和 tfoot 的选择器中添加了您表示您将在生产中使用的选择器。根据您的样本进行相应调整。

    $('table#namedTable').children('tbody,thead,tfoot')
                         .children('tr')
                         .children('td')
    

    【讨论】:

    • 奇怪的是,浏览器自动添加了 tbody (FireFox),因此即使我在源代码中没有 tbody,代码也能正常工作。
    • +1,很好的答案 - 乍一看,这个问题似乎很简单,但事实并非如此。
    【解决方案2】:

    给最外层的表一个id为“Outer”:

    $("table#Outer > td").text("selected");
    

    【讨论】:

    • TD 不是 TABLE 的直接子代。
    • 你必须这样做 $("table#Outer > tbody > tr > td").text("selected");即使我的源代码中没有 tbody,浏览器似乎也会自动将其放入(FF3)