问题描述
我有
var $set = $('.foo,.bar').filter(
function() {return $(this).parents('.baz').length < 1;});
作为一种选择所有类为 foo
或 bar
且不属于类为 baz
.是否有一个选择器可以在不需要过滤 lambda 的情况下完成同样的事情?
as a way to select all the elements whose classes are either foo
or bar
and who do not descend from an element whose class is baz
. Is there a selector that will accomplish the same thing without the need for a filtering lambda?
<div class='foo'/><!--match this-->
<div class='bar'/><!--match this-->
<div class='baz'>
<div class='foo'/> <!--don't match this-->
</div>
推荐答案
事情的真相是,jQuery 根本没有一个特别优雅的方式来做你想做的事.虽然混乱的答案确实有效,但您必须想知道复杂的选择器(与复杂网页中的选择器一样慢)是否值得您拥有更详细但更快的过滤器功能.这并不是什么大不了的事,我个人只是厌倦了特别长、复杂的选择器,但我可以避免它.
The truth of the matter is that jQuery simply does not have a particularly elegant way to do what you want. While chaos' answer does work, you have to wonder whether the complicated selector (that would be about as slow as a selector can be in a complicated webpage) is worth it over the more verbose but faster filter function you have. This is not really that big of a deal, I am just personally weary of particularly long, convoluted selectors when I can avoid it.
另一种选择是创建自己的选择器,因为 jQuery 很棒:
A different option is to create your own selector, since jQuery is awesome:
jQuery.expr[':'].parents = function(a,i,m){
return jQuery(a).parents(m[3]).length < 1;
};
$('.foo,.bar').filter(':parents(.baz)');
expr
映射是 Sizzle 选择器引擎的一部分,可以在此处找到文档:嘶嘶作响的自定义伪选择器
The expr
map is part of the Sizzle selector engine and documentation can be found here: Sizzle Custom Pseudo-Selectors
这篇关于哪个 JQuery 选择器会排除与给定选择器匹配的父项的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!