如何编写“如果不是类”jQuery 选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10216669/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:57:35  来源:igfitidea点击:

How to write "if not class" jQuery selector?

jqueryjquery-selectors

提问by Youss

I want to do something with var p:

我想用 var p 做点什么:

var p = $("li:last");

But I don't want to do anything if there is a certain Class appended. I tried :not like this:

但是如果附加了某个类,我不想做任何事情。我试过:不是这样的:

var p = $("li:last:not(.Class)");

This doesn't work. How can I exclude .Class in my var?

这不起作用。如何在我的 var 中排除 .Class?

回答by bhamlin

var p = $("li:last").not(".Class");

http://api.jquery.com/not/

http://api.jquery.com/not/

回答by cambraca

Actually :notdoes work as a selector.

实际上:not确实作为选择器工作。

If you want to select the last element that doesn't have the class, use this

如果要选择最后一个没有类的元素,请使用此

var p = $("li:not(.Class):last");

This selects first the lis that don't have that class, and thenthe last of them. See it working here.

这首先选择li没有该类的s,然后选择最后一个。看到它在这里工作

To make it perfectly clear, these are equivalent:

为了清楚起见,这些是等效的:

var p = $("li:not(.Class):last");
var p = $("li").not(".Class").last();

And, also, these are equivalent:

而且,这些也是等价的:

var p = $("li:last:not(.Class)");
var p = $("li").last().not(".Class");

回答by osdamv

var p = $("li:last");
if (!p.hasClass('Class')){
//some stuff
}

http://api.jquery.com/hasClass/

http://api.jquery.com/hasClass/