javascript - 使用 jQuery 查找直系子节点,不再继续

标签 javascript jquery

在搜索特定元素时如何获取直接子元素?例如,我想获取表 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,我不明白为什么?

Here是一个完整的例子:

最佳答案

使用:

'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,因为您有两个 <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>

关于javascript - 使用 jQuery 查找直系子节点,不再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385363/

相关文章:

javascript - 如何在 html 中选择没有任何 "div"在 css 中的元素?

javascript - 如何将字符串和函数参数混合到一个变量中

javascript - 我将如何将变量从 .on() 事件传递到回调函数?

javascript - 使用Jquery触发链接的方法

javascript - Jquery从下拉列表更改中更改下拉列表的值

javascript - 如何获取url中的数组值

javascript - 当用户从上向下滚动时滚动到元素

javascript - 我如何重新加载使用 jquery .load 函数加载的特定页面

javascript - jQuery 的交换方法时间成本

javascript - 使用 jQuery/JS 上下切换 DIV 元素