jquery.find()可以仅选择直接子级吗? [英] Can jquery.find() select only direct children?
问题描述
我应该向jQuery.find()提供什么参数来选择子元素而不选择其他元素?我不能使用'>'来引导选择器,而使用'*'将选择所有后代,而不仅是直接子代.
What argument should I provide to jQuery.find() to select the elements children and no other elements? I can't lead the selector with '>' and having '*' will select all descendants, not only direct children.
我知道jQuery.children(),但这是针对库的,因此用户可以提供自己的选择器,并且我想确保他们有某种方式选择直接子代(不添加很多子代)根据我自己的逻辑).
I am aware of jQuery.children(), but this is for a library so the user is able to provide their own selector, and I want to make sure they have some way of selecting just the direct children (without adding lots of my own logic).
编辑
edit
我想使用jQuery.find()
仅查找父元素的第一级子元素内的元素,而不是子元素的子元素.
I want to use jQuery.find()
to only find elements within the first level children of a parent element, not children of children.
示例:
<parent>
<child-1>
<child-2></child-2>
</child-1>
<child-1>
</child-1>
</parent>
我只想搜索元素child-1
而不是其子元素(即child-2)
I want to only search through the elements child-1
and not their children (i.e. child-2)
***
更多说明是在表元素上的Angular指令.该指令需要能够找到表中的行,但是该指令可以用于各种模板,因此它可以具有用于行的选择器.有时,这些行除了是原始元素的子div之外,没有其他明显的特征;在其他时候,这些行是孙子甚至是曾孙.
For more explanation, it is a Angular directive that goes on a table element. The directive needs to be able to find the table rows, but is meant to go on a wide variety of templates so it can have a selector for the rows. Sometimes the rows have no distinct features outside of being child divs to the original element; other times, the rows are grandchildren or even great-grandchildren.
推荐答案
使用问题中提到的>
启动选择器.试试吧:
Start your selector with >
as you mentioned in your question. Try it:
var s = ".classA",
n = $('#wrapper').find('>'+s).length;
alert('Found '+ n +' direct children of #wrapper with the "'+ s +'" selector.'); // 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="wrapper">
<div class="classA"></div> <!-- Selected -->
<div class="classA"> <!-- Selected -->
<div class="classA"></div> <!-- Ignored -->
</div>
<div class="classC">
<div class="classA"></div> <!-- Ignored -->
</div>
<div class="classB">
<div class="classB"></div>
</div>
<div class="classA"></div> <!-- Selected -->
</div>
或使用$.children()
,如您在问题中提到的那样:
Or use $.children()
, as you mentioned it in your question:
var s = ".classA",
n = $('#wrapper').children(s).length;
alert('Found '+ n +' direct children of #wrapper with the "'+ s +'" selector.'); // 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="wrapper">
<div class="classA"></div> <!-- Selected -->
<div class="classA"> <!-- Selected -->
<div class="classA"></div> <!-- Ignored -->
</div>
<div class="classC">
<div class="classA"></div> <!-- Ignored -->
</div>
<div class="classB">
<div class="classB"></div>
</div>
<div class="classA"></div> <!-- Selected -->
</div>
这篇关于jquery.find()可以仅选择直接子级吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!