我正在尝试找出一种使用 jQuery 查找元素但忽略嵌套容器的元素的方法。在下面的示例中,我需要选择第二个“findMe”,但不是第一个。可以有许多区域、 anchor 和其他容器,但只有两层区域。最简单的例子是:
<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...
当我想要将匹配元素集('.zone a')减少为那些不匹配选择器的元素('.zone .zone a')时
例如:
$('.zone a').filterOutThingsThatMatch('.zone .zone a')
.not() 似乎不允许我执行“不具有嵌套容器的事物”要求。
最佳答案
只需对 not
中的嵌套状态进行第二次测试即可:
$anchors = $('.zone a').not('.zone .zone a');
字面上的意思是“在区域类下查找我的所有 anchor ,但如果 anchor 位于区域类下的区域类下则不会”。此版本适用于任何深度,甚至在区域级别之间存在其他 div 的情况下也是如此。
如果您知道它们是固定深度,这可能会更快一点:
$anchors = $('.zone > a').not('.zone > .zone > a');
关于javascript - jQuery 异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31449289/