![](/img/trans.png)
[英]How can I make a function return true after functions within jQuery's .each() finishes?
[英]How can I make jQuery's $.each() function skip certain objects based on criteria?
說我有以下HTML:
<p class="link"><a href="#">This is a link.</a></p>
<p class="link"><a href="#">This is another link.</a></p>
<p class="link current"><a href="#">This is yet another link.</a></p>
<p class="link"><a href="#">This is still another link.</a></p>
我想使用jQuery的$.each()
函數來遍歷帶有類link
所有對象,但我想跳過也有類current
。 我怎么做?
我可以像這樣檢查每個循環中是否存在類:
$('.link').each(function() {
if (!$(this).hasClass('current'))
$(this).fadeOut();
})
...但是有沒有辦法在jQuery中指定“class x,而不是class y”,不再需要if條件?
使用:not()選擇器排除元素:
$('.link:not(.current)').fadeOut();
您可以filter
初始jQuery對象:
$('.link').filter(function() {
return !$(this).hasClass('current');
}).fadeOut();
$('.link').each(function() {
if ($(this).attr('class')!="link current")
$(this).fadeOut();
})
正如Guffa所建議的那樣,你可以使用:not()
CSS偽選擇器。 要將它用於.each()
函數,您可以執行以下操作(請參閱此jsfiddle作為證明):
jQuery(".link:not(.current)").each(function(index, element){
jQuery(element).fadeOut();
});
它適合您的需求嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.