【问题标题】:jQuery: select all elements of a given class, except for a particular IdjQuery:选择给定类的所有元素,除了特定的 Id
【发布时间】:2011-02-02 19:40:15
【问题描述】:

这可能很简单。

我想选择给定类 thisClass 的所有元素,但 id 为 thisId 的除外。

即相当于(其中 -/minus 表示删除):

$(".thisClass"-"#thisId").doAction();

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    使用:not selector

    $(".thisclass:not(#thisid)").doAction();
    

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

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

    【讨论】:

    • 如果要排除多个类怎么办? THX
    • 来自文档:All selectors are accepted inside :not(), for example: :not(div a) and :not(div,a) 所以只需使用逗号分隔的选择器来做多个(".thisclass:not(#thisid,#thatid)").doAction();
    • 像这样使用单引号 - $(".thisclass:not('#thisid')").doAction();
    • 或者如果你想绑定到具有特定类名的元素的所有子元素,除了一个,你可以这样做:$('.thisclass:not(#id) .otherclass') .doAction()
    • 如果我有一个标准代码如:$('#some').notimportant, $('#another').dosomethingelse 并且我想避免在动态给出的特定 id 上执行?
    【解决方案2】:

    或者采用.not()方法

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

    $(".thisClass").not("#thisId").doAction();
    

    【讨论】:

    • .not() 不是选择器。这是一个功能。但也有 :not() 选择器,就像其他答案提到的那样。
    【解决方案3】:

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

    按确切 ID 忽略:

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

    忽略包含单词“Id”的 ID

    $(".thisClass").not('[id*="Id"]').doAction();
    

    忽略以“my”开头的 ID

    $(".thisClass").not('[id^="my"]').doAction();
    

    【讨论】:

      【解决方案4】:

      如果有人正在寻找它,我将只提供一个 JS (ES6) 答案:

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

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

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

      这消除了Array.from 的使用。

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 你的意思是 $(".thisClass[id!='thisId']").doAction(); ?
        【解决方案6】:

        使用.not() 方法选择整个元素也是一种选择。

        如果您想直接对该元素执行其他操作,这种方式可能很有用。

        $(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-19
          • 2011-11-29
          • 1970-01-01
          • 1970-01-01
          • 2021-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多