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

时间:2022-05-20 21:26:29

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"或"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”?

2 个解决方案

#1


210  

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 answer for more info on the differences.

这两种方法之间几乎没有什么区别,除了。not()更可读(特别是当链接)和:not()的速度非常快。有关差异的更多信息,请参见此堆栈溢出答案。

#2


23  

use this..

使用这个. .

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

$("。content_box:不是(.button)”)

#1


210  

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 answer for more info on the differences.

这两种方法之间几乎没有什么区别,除了。not()更可读(特别是当链接)和:not()的速度非常快。有关差异的更多信息,请参见此堆栈溢出答案。

#2


23  

use this..

使用这个. .

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

$("。content_box:不是(.button)”)