什么JQuery选择器排除父项匹配给定选择器的项目? [英] What JQuery selector excludes items with a parent that matches a given selector?
问题描述
我有
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的一部分选择器引擎和文档可以在这里找到: Sizzle Custom Pseudo-Selectors
The expr
map is part of the Sizzle selector engine and documentation can be found here: Sizzle Custom Pseudo-Selectors
这篇关于什么JQuery选择器排除父项匹配给定选择器的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!