简体   繁体   English

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

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

So I tried this: 所以我尝试了这个:

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

I also tried this: 我也试过这个:

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

Both of these does not work. 这两个都不起作用。 The first one will select any TR even if it's under a nested table. 第一个将选择任何TR,即使它在嵌套表下也是如此。 The second one will not work if the table have tbody or anything like that. 如果桌子有肢体或类似的东西,第二个将不起作用。 Any help? 有什么帮助吗?

Input is defined as: 输入定义为:

var input = $(".mySelectionScope");

The DOM would look like this: 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(...);

What about calling first() on the list of trs? 调用trs列表上的first()怎么样?

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

use jQuery children() instead of find() 使用jQuery children()而不是find()

From the docs: 从文档:

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well. .children()方法与.find()的不同之处在于,.children()仅沿DOM树向下移动一个级别,而.find()可以向下遍历多个级别以选择后代元素(孙子等)。

The optional div also creates some trickiness... 可选的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');

if tbody is always inserted in all browsers, the second if statement is not necessary, and you can instead use 如果在所有浏览器中始终插入了tbody,则不需要第二个if语句,而可以使用

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

Pretty ugly, but you can't do this with selectors alone. 非常难看,但您不能仅凭选择器来做到这一点。

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

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

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

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