jQuery在选择器中排除具有特定类的元素


127

我想在jQuery中为某些锚标签设置点击事件触发器。

我想在新选项卡中打开某些链接,而忽略具有特定类的链接(在您问我无法将类放在我试图捕获的链接上之前,因为它们来自CMS)。

我想排除类别为"button"OR的链接"generic_link"

我努力了:

$(".content_box a[class!=button]").click(function (e) {
    e.preventDefault();     
    window.open($(this).attr('href'));
});

但这似乎不起作用,还应该如何做一个OR语句以包括"generic_link"在排除中?

Answers:


263

您可以使用.not()方法:

$(".content_box a").not(".button")

另外,您也可以使用:not()选择器:

$(".content_box a:not('.button')")

两种方法之间几乎没有什么区别,除了.not()可读性更强(特别是在链接时)而且:not()速度稍快。有关差异的更多信息,请参见此堆栈溢出答案


1
所以我可以做:$(“。content_box a”)。not(“。button”)。not(“。generic_link”)。click(function(e)...?
Titan

1
即使使用,效果也完美.each()
cfx

使用时似乎存在错误.text()-使用say删除的元素.not的文本仍在文本中。
Netsi1964


2

要添加一些今天对我有帮助的信息,this还可以将jQuery object / 传递给.not()选择器。

$(document).ready(function(){
    $(".navitem").click(function(){
        $(".navitem").removeClass("active");
        $(".navitem").not($(this)).addClass("active");
    });
});
.navitem
{
    width: 100px;
    background: red;
    color: white;
    display: inline-block;
    position: relative;
    text-align: center;
}
.navitem.active
{
    background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="navitem">Home</div>
<div class="navitem">About</div>
<div class="navitem">Pricing</div>

上面的例子中可以被简化,但想显示的使用thisnot()选择器。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.