【问题标题】:selector in JavascriptJavascript中的选择器
【发布时间】:2018-11-23 11:17:25
【问题描述】:

我是 Javascript 的初学者。我有一个链接列表,我想选择以 .zip 结尾的链接并从 css 添加类 zip;

添加选择链接以非 .zip 结尾并从 css 添加类 notzip。

我用 $("a[href $='.zip']").addClass("zip") 做第一个任务,但不能通过 add 完成任务 2!或不()。由 $this 和 location、filter 功能推荐。我怎样才能做到这一点?

      <ul>
    <li><a href="a.html">a</a></li>
    <li><a href="b.pdf">b</a></li>
    <li><a href="c.zip">c</a></li>
  </ul>

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    您可以使用:not:

    $(function() {
      $("a[href$='.zip']").addClass('zip');
      $("a:not([href$='.zip'])").addClass('notzip');
      $("a:not([href$='.zip']):not([href$='.html'])").addClass('notzipnorhtml');
      
      var exts = ['html', 'pdf', 'zip'];
      $('a' + exts.map(ext => ':not([href$=".' + ext + '"])').join(''))
        .addClass('notanyofthose');
    });
    .zip { color: green; }
    .notzip { color: red; }
    .notzipnorhtml { color: purple; }
    .notanyofthose { color: blue; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
      <li><a href="a.html">a</a></li>
      <li><a href="b.pdf">b</a></li>
      <li><a href="c.zip">c</a></li>
      <li><a href="d.exe">d</a></li>
    </ul>

    【讨论】:

    • 谢谢。有用。当我之前使用“不”时,似乎问题出现在逻辑部分。 $("a:not([href$='.zip'])").addClass('notzip'); 覆盖$("a[href$='.zip']").addClass('zip'); 的结果,当将类“notzip”添加到不带 .zip 或 .html 后缀的 href 时。为什么会这样?
    • @JiayanYang 我不明白你的问题。你能说明你在你的情况下是如何使用:not的,看看可能出了什么问题吗?
    • @JetoThe :not 运作良好。但是,当我 $("a:not([href$='.zip||.html)'])").addClass("download"); 时,结果覆盖了 $("a[href$='.zip']").addClass('zip');。在您的示例中,绿色也变为红色。
    • $("a:not([href$='.zip||.html)'])") 不正确。你想达到什么目的?您想匹配不以 .zip 或 .html 结尾的任何内容?
    • @JetoExactly。想要查找除以 .zip 或 .html 结尾的 href 以外的任何内容。这就是为什么我说“当我之前使用“not()”时,问题似乎出现在逻辑部分。对不起我的英语不好:)
    【解决方案2】:

    如果我理解正确, 这应该工作!

    $("a[href='.zip']").addClass("zip");
    $("a[href!='.zip']").addClass("notzip");
    

    【讨论】:

    • @testingKikiHi 感谢您的建议。我认为href='.zip' 应该是href $= '.zip',因为我需要为href 结尾添加.zip 类。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2019-04-11
    • 2013-04-04
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多