jQuery是否有类似于:any或:matches伪类?

时间:2014-01-24 18:01:25

标签: jquery css jquery-selectors css-selectors

我想简化我的选择器:

'#a #b a[href^=mailto], .c .d a[href^=mailto]'

要:

':matches(#a #b, .c .d) a[href^=mailto]'

这可能只使用jQuery选择器吗?或者我必须这样做:

$('#a #b, .c .d').find('a[href^=mailto]')

哪个不灵活。

4 个答案:

答案 0 :(得分:3)

jQuery没有提供相当于:any() / :matches()的选择器(其中:any()是原始形式和it was first implemented internally in Gecko and WebKit)。如果您不能或不愿意扩展选择器,您将必须分解选择器字符串并进行单独的方法调用。

您使用哪种方法取决于:matches()在选择器中的显示位置:

  • 如果:matches()单独出现在选择器字符串的开头,则在任何组合器之前,如问题所示:

    ':matches(#a #b, .c .d) a[href^=mailto]'
    

    替换显示$()的{​​{1}},并将选择器的其余部分传递给:matches().find().children().next(),具体取决于分别跟.nextAll()(后代,子,:matches()+)的组合子。

    转载自问题:

    ~
  • 如果$('#a #b, .c .d').find('a[href^=mailto]') 在组合子后出现,例如:

    :matches()

    替换出现'#a #b > :matches(.c, .d)' 的上述方法之一:

    :matches()
  • 如果$('#a #b').children('.c, .d') 作为另一个复合选择器的一部分出现,例如:

    :matches()

    替换出现':matches(#a #b, .c .d) a[href^=mailto]:matches(.e, .f)' 的地方.filter()

    :matches()

答案 1 :(得分:1)

他们有 .has() ,它将匹配元素的集合减少为具有与选择器或DOM元素匹配的后代的元素。

因此,这将返回 父对象 ,其中包含一个以mailto开头的href的锚:

$('#a #b, .c .d').has('a[href^=mailto]');

但就选择锚点本身而言,最后一个选项 find() 是最佳选择。它本质上是任何其他方法的封面。

$('#a #b, .c .d').find('a[href^=mailto]');

答案 2 :(得分:1)

如果您正在寻找所有a[href^=mailto],那么

$('a[href^=mailto]')....

$('* a[href^=mailto]')....

如果他们有“通用”选择器/父母

$('selector * a[href^=mailto]')....

否则:

你在问题中写的

$('#a #b, .c .d').find('a[href^=mailto]')

答案 3 :(得分:0)

此时没有你在jQuery中提到的选择器。

似乎你最后的选择器已经是最简化的方式了,如果有什么可以缩短的话:

$('#b, .c .d').find('a[href^=mailto]')

如果您需要#b作为#a的后代,那么就无法缩短您的选择器IMO

相关问题