【问题标题】:Recursively searching for top level of matching elements递归搜索顶级匹配元素
【发布时间】:2013-06-26 18:39:46
【问题描述】:

假设我有一些如下所示的 HTML,并且我想搜索具有 foo 类的 #top 元素的后代。但是,我只想找到不是我找到的其他元素的子元素的元素。也就是说,虽然通常我想递归搜索 foo 元素,但我不想递归到 foo 元素。

<div class="foo" id="top">
    <div class="bar">
        <div class="foo"> <!-- Find this !-->
        </div>
    </div>
    <div class="foo"> <!-- Find this !-->
        <div class="foo"> <!-- Do not find this, because we already found parent !-->
        </div>
    </div>
</div>

我怎样才能最好地使用 Javascript/jQuery 做到这一点?

编辑:对此存在一些混淆。上面的例子是为了说明问题,但它并没有封装通用解决方案应该解决的所有边缘情况,所以我在这里创建了一个更复杂的例子:http://jsfiddle.net/JQNyW/1/

【问题讨论】:

  • 我们是否应该假设这不是确切的结构,因此嵌套级别实际上可能会有所不同?
  • @CrazyTrain,是的,绝对是

标签: javascript jquery html search jquery-selectors


【解决方案1】:

像这样?

$('#top').find('.foo').filter(function () { // while selecting ignore parent which also has foo
    return $(this).parents('.foo').length == 1; //length is 1 since the #top also has foo
});

Fiddle

或者

$('#top').find('.foo').filter(function () {
    return $(this).parents('.foo:not("#top")').length == 0
}).css('color', 'red');

【讨论】:

  • +1 虽然您可以删除 :not("#top"),因为 .find() 不查看上下文节点。
  • 废话,谢谢你是对的.. /:(。辛苦的一天工作.. :) 不知道我在想什么...聚会时间..
  • 嗯,不完全是,因为我不想对我提供的外部结构做出任何假设......例如,#top 可能在另一个foo 中,就像这样:jsfiddle.net/ZYytY/3。但我认为对您的解决方案的这个小调整可以解决这个问题:jsfiddle.net/ZYytY/4
  • ...甚至return $(this).parents("#top .foo").length == 0;
  • @CrazyTrain 第二个是你能得到的最好的...$('#top').find('.foo').filter(function () { return $(this).parents("#top .foo").length == 0; }).css('color', 'red');
【解决方案2】:

我可能会单独使用 children() 或 find(),因为它们不需要链接来访问孩子的孩子,这使它更清洁、优化和更快地处理,如下所示:

 $('#top').children('.foo').attr('this','yeah');

 $('#top').find('> .foo',this).attr('child','yes');

看一下控制台,它只将 att() 添加到第一个元素。

根据您的需要参考 jQuery 中的文档:

http://api.jquery.com/find/

http://api.jquery.com/children/

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    您可以使用以下选择器:

    #top > .foo, :not(.foo) > .foo
    

    在 jQuery 或原生 JavaScript 中。

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      相关资源
      最近更新 更多