问题
I want to simplify my selector from:
'#a #b a[href^=mailto], .c .d a[href^=mailto]'
To:
':matches(#a #b, .c .d) a[href^=mailto]'
Is this possible just using jQuery selectors? Or do I have to do this:
$('#a #b, .c .d').find('a[href^=mailto]')
Which isn't as flexible.
回答1:
jQuery does not provide a selector equivalent of :any()
/:matches()
(of which :any()
was the original form and it was first implemented internally in Gecko and WebKit). You will indeed have to break up your selector strings and make separate method calls, if you are unable or unwilling to expand your selector.
Which method(s) you use depends on where exactly :matches()
would appear in your selector:
If
:matches()
appears by itself in the beginning of the selector string, before any combinators, as in the question:':matches(#a #b, .c .d) a[href^=mailto]'
Substitute
$()
where:matches()
appears, and pass the remainder of the selector to.find()
,.children()
,.next()
or.nextAll()
depending on the combinator that follows:matches()
(descendant, child,+
, or~
respectively).Reproduced from the question:
$('#a #b, .c .d').find('a[href^=mailto]')
If
:matches()
appears by itself after a combinator, for example:'#a #b > :matches(.c, .d)'
Substitute one of the above methods where
:matches()
appears:$('#a #b').children('.c, .d')
If
:matches()
appears as part of another compound selector, for example:':matches(#a #b, .c .d) a[href^=mailto]:matches(.e, .f)'
Substitute
.filter()
where that:matches()
appears:$('#a #b, .c .d').find('a[href^=mailto]').filter('.e, .f')
回答2:
if you are looking for all a[href^=mailto]
, then
$('a[href^=mailto]')....
AND
$('* a[href^=mailto]')....
OR if they have a "universal" selector/parent
$('selector * a[href^=mailto]')....
otherwise:
$('#a #b, .c .d').find('a[href^=mailto]')
as you wrote in your question
回答3:
They have .has() which reduces the set of matched elements to those that have a descendant that matches the selector or DOM element.
So this would return the parent objects that have an anchor with an href beginning with mailto:
$('#a #b, .c .d').has('a[href^=mailto]');
But as far as selecting the anchors themselves, your last option, find(), is best. It essentially is what would be called anyway under the covers from any other method.
$('#a #b, .c .d').find('a[href^=mailto]');
回答4:
There's no selector like you mention in jQuery at this moment.
Seem like your last selectors is the most simplified way already, if anything can do to shorten than only:
$('#b, .c .d').find('a[href^=mailto]')
If you require #b
as the descendent of #a
, then there's no way to shorten your selector IMO
来源:https://stackoverflow.com/questions/21339353/does-jquery-have-something-like-the-any-or-matches-pseudo-class