问题描述
给定以下假设标记:
<ul class="monkey">
<li>
<p class="horse"></p>
<p class="cow"></p>
</li>
</ul>
<dl class="monkey">
<dt class="horse"></dt>
<dd class="cow">
<dl>
<dt></dt>
<dd></dd>
</dl>
<dl class="monkey">
<dt class="horse"></dt>
<dd class="cow"></dd>
</dl>
</dd>
</dl>
我希望能够在每个猴子类中获得马和牛类的第一级".但我不想要 NESTED 马和牛类.
I want to be able to grab the 'first level' of horse and cow classes within each monkey class. But I don't want the NESTED horse and cow classes.
我从 .children 开始,但这不适用于 UL 示例,因为它们不是 .monkey 的直接子代.
I started with .children, but that won't work with the UL example as they aren't direct children of .monkey.
我可以使用 find: $('.monkey').find('.horse, .cow') 但它返回所有实例,包括嵌套的实例.
I can use find: $('.monkey').find('.horse, .cow') but that returns all instances, including the nested ones.
我可以过滤查找: $('.monkey').find('.horse, .cow').not('.cow .horse, .cow .cow') 但这会阻止我选择嵌套实例在第二个函数调用中.
I can filter the find: $('.monkey').find('.horse, .cow').not('.cow .horse, .cow .cow') but that prevents me from selecting nested instances on a second function call.
所以......我想我正在寻找的是'找到这个后代的第一个级别"'.我可能会用一些循环逻辑来做到这一点,但想知道是否有一个选择器和/或一些选择器组合可以实现该逻辑.
So...I guess what I'm looking for is 'find first "level" of this descendant'.I could likely do this with some looping logic, but was wondering if there is a selector and/or some combo of selectors that would achieve that logic.
更新:
这是我最后的结果:
$('.monkey')
.children('.cow')
...do something...
.end()
.children('li')
.children('.cow')
...do something...
.end()
.end()
看起来冗长/笨拙但似乎有效.
Seems verbose/hacky but seems to work.
推荐答案
使用子元素,因为它为您提供直接的子元素.
Use the children, as it give you the immediate child elements.
$(".monkey").children(".horse, .cow, li > .horse, li > .cow")
已编辑
$(".monkey, .monkey > li").children(".horse, .cow")
这篇关于通过jQuery选择类的第一个实例而不是嵌套实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!