jQuery:选择给定类的所有元素,但特定的Id除外

Ank*_*kur 141 jquery jquery-selectors

这可能很简单.

我想选择给定类的所有元素thisClass,除非id是thisId.

即相当于(其中 - /减号暗示删除)的东西:

$(".thisClass"-"#thisId").doAction();
Run Code Online (Sandbox Code Playgroud)

rah*_*hul 276

使用:not selector.

$(".thisclass:not(#thisid)").doAction();
Run Code Online (Sandbox Code Playgroud)

如果你有多个id或选择器,只需使用逗号分隔符,另外:

(".thisclass:not(#thisid,#thatid)").doAction();

  • 从文档:`所有选择器都被接受:not(),例如:: not(div a)和:not(div,a)`所以只需使用逗号分隔的选择器来做多个`(".这个类:不是(#thisid,#thatid)")doAction();` (13认同)
  • 如果要排除多个类,该怎么办?谢谢 (3认同)

Kar*_*ler 29

或者使用.not()方法

https://api.jquery.com/not/

$(".thisClass").not("#thisId").doAction();
Run Code Online (Sandbox Code Playgroud)

  • `.not()`不是选择器.这是一个功能.但是还有其他答案提及的`:not()`选择器. (3认同)

Sco*_*tyG 8

您可以像以下示例一样使用.not函数来删除具有确切 id、包含特定单词的 id、以单词开头的 id 等的项目...请参阅http://www.w3schools.com/jquery/jquery_ref_selectors .asp了解更多关于 jQuery 选择器的信息。

按确切 ID 忽略:

 $(".thisClass").not('[id="thisId"]').doAction();
Run Code Online (Sandbox Code Playgroud)

忽略包含“Id”一词的 ID

$(".thisClass").not('[id*="Id"]').doAction();
Run Code Online (Sandbox Code Playgroud)

忽略以“my”开头的 ID

$(".thisClass").not('[id^="my"]').doAction();
Run Code Online (Sandbox Code Playgroud)


Jay*_*wal 6

我会抛出一个JS(ES6)答案,以防有人在寻找它:

Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
    doSomething(el);
}
Run Code Online (Sandbox Code Playgroud)

更新(这可能是我发布原始答案时可能的,但无论如何现在添加此答案):

document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
    doSomething(el);
});
Run Code Online (Sandbox Code Playgroud)

这摆脱了Array.from使用.

document.querySelectorAll返回一个NodeList.
阅读此处以了解有关如何迭代它(以及其他内容)的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/NodeList


Amy*_*y B 5

$(".thisClass[id!='thisId']").doAction();

关于选择器的文档:http://api.jquery.com/category/selectors/

  • 代码示例中是否缺少']'? (9认同)
  • 你的意思是$(".thisClass [id!='thisId']").doAction(); ? (5认同)