查找直系亲属,不再使用jQuery

Find immediate children and go no further using jQuery

本文关键字:jQuery 不再 直系亲属 查找      更新时间:2023-09-26

在搜索特定元素时,如何获取直属子项?例如,我想要获得表t1tr元素。

    <table id="t1" bgcolor="yellow">
        <tbody>
            <tr>
                <td>This is Cell 1</td>
                <td>This is Cell 2</td>
            </tr>
            <tr>
                <td>This is Cell 3</td>
                <td>
                    <table id="t2" bgcolor="red">
                        <tbody>
                            <tr>
                                <td>This is Cell 1</td>
                                <td>This is Cell 2</td>
                            </tr>
                            <tr>
                                <td>This is Cell 3</td>
                                <td>This is Cell 4</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>

我试过这个:

'Count = ' + $('#t1 tbody').children('tr').length;

然而,我得到了4的计数,我不明白为什么?

下面是一个完整的示例:

使用:

'Count = ' + $('#t1 > tbody').children('tr').length;
//  or: $("#t1 > tbody > tr").length
//  or: $("#t1")[0].rows.length; // In this case, equal to previous code.
                                 // Warning: This also includes the rows from
                                 //  the <thead> and <tfoot> sections.

您当前的代码显示4,因为表#t1:中有两个<tbody>元素

<table id="t1" bgcolor="yellow">           <-- #t1
    <tbody>                                <--- tbody
        <tr> ... </tr>                     <----- Child 1
        <tr> ...                           <----- Child 2
                    <tbody>                <--- tbody (unexpected?)
                        <tr> ... </tr>     <----- Child 3
                        <tr> ... </tr>     <----- Child 4
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

这是因为使用$('#t1 tbody')可以从两个表中获得tbody

您可以直接使用Child Selector (“parent > child”)docs

$('#t1 > tbody > tr').length;

这是您更新的示例:http://jsfiddle.net/SvygZ/1/