jQuery jQuery在选择器中排除具有特定类的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3015103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery exclude elements with certain class in selector
提问by Titan
I want to setup a click event trigger in jQuery for certain anchor tags.
我想在 jQuery 中为某些锚标记设置一个点击事件触发器。
I want to open certain links in a new tab while ignoring ones with a certain class (before you ask I cannot put classes on the links I am trying to catch as they come from a CMS).
我想在新选项卡中打开某些链接,同时忽略具有某个类的链接(在您问之前,我无法将类放在我试图捕获的链接上,因为它们来自 CMS)。
I want to exclude links with class "button"
OR "generic_link"
我想排除与类"button"
OR 的链接"generic_link"
I have tried:
我试过了:
$(".content_box a[class!=button]").click(function (e) {
e.preventDefault();
window.open($(this).attr('href'));
});
But that doesn't seem to work, also how do I do an OR statement to include "generic_link"
in the exclusion?
但这似乎不起作用,我如何执行 OR 语句以包含"generic_link"
在排除中?
回答by Pranay Rana
You can use the .not()method:
您可以使用.not()方法:
$(".content_box a").not(".button")
Alternatively, you can also use the :not()selector:
或者,您也可以使用:not()选择器:
$(".content_box a:not('.button')")
There is little difference between the two approaches, except .not()
is more readable (especially when chained) and :not()
is very marginally faster. See this Stack Overflow answerfor more info on the differences.
这两种方法之间几乎没有区别,只是.not()
可读性更高(尤其是链接时)并且:not()
速度非常快。有关差异的更多信息,请参阅此堆栈溢出答案。
回答by sushil bharwani
use this..
用这个..
$(".content_box a:not('.button')")
$(".content_box a:not('.button')")
回答by Vignesh Raja
To add some info that helped me today, a jQuery object/this
can also be passed in to the .not()selector.
要添加一些今天对我有帮助的信息,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>
The above example can be simplified, but wanted to show the usage of this
in the not()
selector.
上面的例子可以简化,但想展示this
在not()
选择器中的用法。