jQuery 异或

jQuery Exclusive OR

我正在尝试找出一种方法来查找具有 jQuery 的元素,但忽略嵌套容器的元素。在下面的示例中,我需要 select 第二个 'findMe' 而不是第一个。之间可以有许多区域、锚点和其他容器,但只有两层区域。最简单的例子是:

<div class="zone">
    <div class="zone">
        <a class="findMe"></a>
    </div>
    <a class="findMe"></a>
</div>

即:我正在寻找类似独家或:

$allZoneAnchors = $('.zone a');
$nestedAnchors = $('.zone .zone a');
//Then somehow XOR $allZoneAnchors and $nestedAnchors

jQuery .filter 看起来很有趣但是你用它来

Reduce the set of matched elements to those that match the selector...

当我想要的是 将匹配元素集 ('.z​​one a') 减少到不匹配 select 或 ('.z​​one .zone a' )

例如:

$('.zone a').filterOutThingsThatMatch('.zone .zone a')

.not() 似乎不允许我执行 "not things that have a nested container" 要求。

只需对 not:

中的嵌套状态进行第二次测试
$anchors = $('.zone a').not('.zone .zone a');

字面意思是 "find my all anchors under zone classes, but not if the anchor is under a zone class which is under a zone class"。此版本适用于任何深度,即使区域级别之间存在其他 div。

如果你知道它们是固定深度,这可能会快一点:

$anchors = $('.zone > a').not('.zone > .zone > a');

如果我理解正确,您可以使用单个 CSS 选择器:

 var $nestedAnchors  = $(':not(.zone) .zone a');

您将匹配不在另一个 .zone

下的所有 .zones

:not(.zone)*:not(.zone) 的快捷方式,因此除 '.zone' 之外的任何元素

或jQuery.not()

var $('.zone a').not('.zone .zone a');

因为选择器的复杂性 jQuery 解决方案可能要快得多。