javascript jQuery递归查找子项,但忽略某些元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6368609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:25:19  来源:igfitidea点击:

jQuery finding children recursively, but ignore certain elements

javascriptjqueryhtmljquery-selectors

提问by Arun

Lets assume the following HTML

让我们假设以下 HTML

<div id=main>
   <div id=a></div>
   <div id=b></div>
   <div id=c></div>
   <div id=d>
      <div id=d1 class="no">
        <div id=d11></div>
        <div id=d12></div>
      </div>
   </div>
   <div id=e>
      <div id=e1 class="no">
        <div id=e11></div>
        <div id=e12></div>
        <div id=e13></div>
      </div>
   </div>
 </div>

I want to select all div tags that are children of main, but want to ignore children of divs that have a class as "no".

我想选择作为 main 子级的所有 div 标签,但想忽略类为“no”的 div 子级。

I have currently written a recursive function to do the job. But was wondering if there is a jQuery selector to get what I want.

我目前已经编写了一个递归函数来完成这项工作。但想知道是否有一个 jQuery 选择器来获得我想要的。

I want the DIVs with ids a,b,c,d,d1,e,e1

我想要 ID 为 a,b,c,d,d1,e,e1 的 DIV

Thanks

谢谢

EDIT: Created a test page here - http://jsfiddle.net/mRENV/

编辑:在这里创建了一个测试页面 - http://jsfiddle.net/mRENV/

回答by Felix Kling

It should be:

它应该是:

$('#main div').not('.no div')

Btw. the term childrenonly refers to the directdescendants of an element. You want to get all descendants (not only children) of #main.

顺便提一句。术语children仅指元素的直接后代。您想获得 . 的所有后代(不仅仅是孩子)#main

Reference:.not()

参考:.not()

Edit:Updated your demo so that it works properly: http://jsfiddle.net/fkling/mRENV/1/

编辑:更新您的演示,使其正常工作:http: //jsfiddle.net/fkling/mRENV/1/

回答by jAndy

Several syntactical ways to achieve that using jQuery, my suggestion is:

使用 jQuery 实现的几种语法方法,我的建议是:

var $result = $('#main').find('div:not(.no > div)');

Invoking .find()helpalong with the pseudo :not()helpselector. This line is equivalent to:

与伪帮助选择器一起调用.find()帮助。这一行相当于::not()

var $result = $('#main').find('div').not('.no > div');

while the latter might be slightly faster.

而后者可能会稍微快一点。

回答by Useless Code

In a single selector with no further traversal you could do this: $('#main div:not(div.no > div)');

在没有进一步遍历的单个选择器中,您可以这样做: $('#main div:not(div.no > div)');