Javascript 中的选择器
selector in Javascript
我是 Javascript 的初学者。我有一个链接列表,我想 select 链接以 .zip 结尾并添加 class zip from css;
添加 select 以非 .zip 结尾的链接并从 css 添加 class notzip。
我用
$("a[href $='.zip']").addClass("zip")
可以做第一个任务,但是不能做第二个任务!或不()。推荐$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>
你可以利用: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[href='.zip']").addClass("zip");
$("a[href!='.zip']").addClass("notzip");
我是 Javascript 的初学者。我有一个链接列表,我想 select 链接以 .zip 结尾并添加 class zip from css;
添加 select 以非 .zip 结尾的链接并从 css 添加 class notzip。
我用
$("a[href $='.zip']").addClass("zip")
可以做第一个任务,但是不能做第二个任务!或不()。推荐$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>
你可以利用: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[href='.zip']").addClass("zip");
$("a[href!='.zip']").addClass("notzip");