繁体   English   中英

在jQuery中,如何选择当前表TR,而不选择任何嵌套表TR?

[英]In jQuery, how do you select current table TR but not any nested table TR?

所以我尝试了这个:

input.find(" tr").each(function(){ ... });

我也试过这个:

input.find(" > tr").each(function(){ ... });

这两个都不起作用。 第一个将选择任何TR,即使它在嵌套表下也是如此。 如果桌子有肢体或类似的东西,第二个将不起作用。 有什么帮助吗?

输入定义为:

var input = $(".mySelectionScope");

DOM如下所示:

    <div class='mySelectionScope'>
        <div> // Optional
            <table>
                <tbody>
                    <tr>  // Select this one
                        <table>
                            <tr>  // Don't select this one
                            ....

您可以使用.not()在tr的下面过滤掉tr的内容

input.find("tr").not("tr tr")

您可以过滤它:

input.find("tr").filter(function(){return !$(this).closest('tr').length}).each(...);

调用trs列表上的first()怎么样?

http://api.jquery.com/first/

使用jQuery children()而不是find()

从文档:

.children()方法与.find()的不同之处在于,.children()仅沿DOM树向下移动一个级别,而.find()可以向下遍历多个级别以选择后代元素(孙子等)。

可选的div也会带来一些棘手的问题...

var input = $('.mySelectionScope').children('div').length == 0 ?
        $('.mySelectionScope') : 
        $('.mySelectionScope > div'),
    rows = input.children('table').children('tbody').length == 0 ?
        input.children('table').children('tr') :
        input.children('table').children('tbody').children('tr');

如果在所有浏览器中始终插入了tbody,则不需要第二个if语句,而可以使用

    rows = input.children('table').children('tbody').children('tr');

非常难看,但您不能仅凭选择器来做到这一点。

使用此解决方案,之间是否有tbody标签并不重要:

$('table').find('tr:first').parent().children()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM