【发布时间】:2014-06-19 15:31:56
【问题描述】:
这似乎是一个简单的问题,但我在解决这个问题时遇到了一些麻烦。给出的示例是SSCCE,我有一个更大的问题试图解决。为了使它工作,查询不能包含任何直接子选择器 (>),因为 dom 树比这个例子复杂一点。
我的目标是选择所有不在包含类的父级之下的子级。在此示例中,我尝试选择 2 个 div 容器 hello 和 world,但不选择 foo 和 bar。
这是一个 plunker,其中包含代码以方便您使用。 http://plnkr.co/edit/4zsKAFts5X7X2kLADj2V?p=preview
使用此 HTML:
<div id="root" class="parent">
<div>
<div class="child">hello</div>
<div class="child">world</div>
</div>
<div class="parent">
<div>
<div class="child">foo</div>
<div class="child">bar</div>
</div>
</div>
</div>
还有这个 Javascript:
var root = $('#root');
$(':not(.parent) .child', root).css('font-weight', 'bold');
我看到了这个结果:
你好
世界
富
条形
但我想得到的是
你好
世界
富
酒吧
重申一下,我想从给定节点(在本例中为 #root)开始,获取所有类为 child 且没有父类为 parent 的元素。
【问题讨论】:
-
I want to get all elements with class child who dont have a parent with class parent根有parent类,所以我不确定您对这项工作有何期待? -
我想我想将查询限制在给定的节点上,在本例中为
root -
正如您规定的“从给定节点开始”,您应该使用将根节点作为参数而不使用硬连线选择器常量的版本,例如:
var root = $('#root'); $('.child', root).not(root.find(".parent .child")).css('font-weight', 'bold');或 @987654337 @ -
@TrueBlueAussie 好吧,这只是我为了说明我遇到的问题而编造的一个小例子,我的实际代码看起来不像这样。
标签: javascript jquery jquery-selectors