找到直接的孩子,不再使用jQuery了

Abs*_*Abs 1 javascript jquery

在搜索特定元素时如何让直系孩子?例如,我想获取tr表的元素t1.

    <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>
Run Code Online (Sandbox Code Playgroud)

我试过这个:

'Count = ' + $('#t1 tbody').children('tr').length;
Run Code Online (Sandbox Code Playgroud)

但是,我算了4,我不明白为什么?

是一个完整的例子:

Rob*_*b W 5

使用:

'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.
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)