繁体   English   中英

如何让jQuery的$ .each()函数根据条件跳过某些对象?

[英]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.

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