【问题标题】:jQuery exclude elements with certain class in selectorjQuery在选择器中排除具有特定类的元素
【发布时间】:2011-03-02 04:50:33
【问题描述】:

我想在 jQuery 中为某些锚标签设置一个点击事件触发器。

我想在新选项卡中打开某些链接,同时忽略具有特定类的链接(在你问我不能将类放在我试图捕获的链接上,因为它们来自 CMS)。

我想排除带有 "button""generic_link"

类的链接

我试过了:

$(".content_box a[class!=button]").click(function (e) {
    e.preventDefault();     
    window.open($(this).attr('href'));
});

但这似乎不起作用,我如何执行 OR 语句以将 "generic_link" 包含在排除项中?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    使用这个..

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

    【讨论】:

      【解决方案2】:

      您可以使用.not() 方法:

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

      或者,您也可以使用:not() 选择器:

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

      这两种方法几乎没有区别,除了.not() 更具可读性(尤其是在链接时)和:not() 非常快。有关差异的更多信息,请参阅this Stack Overflow answer

      【讨论】:

      • 所以我可以这样做:$(".content_box a").not(".button").not(".generic_link").click(function (e)...?跨度>
      • 工作完美,即使使用.each()
      • 使用.text()时似乎有一个错误-使用.not删除的元素的文本仍在文本中。
      【解决方案3】:

      要添加一些今天对我有帮助的信息,也可以将 jQuery 对象/this 传递给 .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>

      上面的例子可以简化,但是想展示thisnot()选择器中的用法。

      【讨论】:

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