jQuery:选择除具有特定子对象和特定属性的元素以外的所有元素 [英] Jquery: select all elements except one with specific child with specific attribute

查看:67
本文介绍了jQuery:选择除具有特定子对象和特定属性的元素以外的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的东西:

<div class="testdiv">
    <a href="/link1">link 1</a>
</div>
<div class="testdiv">
    <a href="/link2">link 2</a>
</div>
<div class="testdiv">
    <a href="/link3">link 3</a>
</div>
<div class="testdiv">
    <a href="/link4">link 4</a>
</div>

现在我要选择类testdiv的所有<div>,除了div具有属性href="/link3"的子<a>之外,如何使用jQuery?

Now I want select all <div>s of class testdiv except the div that has a child <a> with attribute href="/link3", how to do that with jQuery?

我知道我可以做到:

$('div.testdiv')

推荐答案

使用:not + :has可以使用一个选择器轻松完成:

With :not + :has it can be done easily with one selector:

$('div.testdiv:not(:has(a[href="/link3"]))')

如果您未在属性("CSS标识符")中引用值,则需要使用两个反斜杠(\\)来对斜杠(/)进行转义:

If you don't quote the value in the attribute ("CSS identifiers") you need to escape the slash(/) with two backslashes (\\):

$('div.testdiv:not(:has(a[href=\\/link3]))')

实时演示

如果div中只能有一个锚,则可以使用以下方法:

If There can be only one anchor in a div, you can use this:

$('div.testdiv:has(a[href!="\\/link3")')

这篇关于jQuery:选择除具有特定子对象和特定属性的元素以外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆