【问题标题】:Multiple search patterns (equals plus not equals)多种搜索模式(等于加不等于)
【发布时间】:2014-12-08 23:12:35
【问题描述】:

在 JQuery 中我正在尝试执行以下操作

  1. 找到页面上的每个链接
  2. HREF 属性以“#”开头的位置
  3. 并且 ID 值不是“mobileMenu”

这很好用:

$("a[href^='#']").each(function () { // links where HREF starts with #
    if ($(this).attr('id') != 'mobileMenu') { // id not equal to mobileMenu
        $(this).click(function () {
            // logic
        })
    }
});

但是当我尝试将它组合成更简洁的搜索时,它失败了(mobileMenu 链接仍然被拉入数组):

$("a[href^='#'], a[id!='mobileMenu']").each(function () {

}

请问我做错了什么?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你不应该使用多重选择器,因为你想要一个 AND 条件

    $('a[href^="#"]:not(#mobileMenu)').each(...)
    

    【讨论】:

    • +1。 :not.not() 效率更高 jsperf.com/jquery-css3-not-vs-not
    • @Terry,文档说'最好使用 .not() 而不是 $('x:not(y)')'
    • CSS3 选择器通常更快。 Check this link,在浏览器中测试。你有你的答案。 jQuery doc 推荐 .not() 只是因为它 makes the code more readable 而不是将伪选择器组合在一起。
    • @Terry 这将取决于传递给 not() - jsperf.com/jquery-css3-not-vs-not-2 的内容 - 这里一个非 css3 :not() 支持的选择器被传递给 not() 在这种情况下 .not() 更好比:not()
    • @ArunPJohny Well * 通常是一个非常昂贵的选择器:P
    【解决方案2】:

    试试这个:使用.not() 从选定的元素列表中排除元素。

    $("a[href^='#']").not('#mobileMenu').each(function () {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多