简体   繁体   English

JavaScript中的选择器

[英]selector in Javascript

I'm beginner in Javascript. 我是Java语言的初学者。 I have a list of links and I want to select links end with .zip and add class zip from css; 我有一个链接列表,我想选择以.zip结尾的链接,并从CSS添加类zip;

add select links end with not .zip and add class notzip from css. 添加选择链接以非.zip结尾,并从CSS添加类notzip。

I use $("a[href $='.zip']").addClass("zip") to do the first task but cannot do the task 2 by add ! 我使用$("a[href $='.zip']").addClass("zip")来执行第一个任务,但是不能通过add执行任务2! or not(). 或不()。 It is recommended by $this and location, filter function. 由$ this和location,filter功能推荐。 How can I do that? 我怎样才能做到这一点?

      <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>

You can make use of :not : 您可以使用: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> 

If I understood correctly, this should work! 如果我理解正确,那应该可以!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM