2013-02-27 58 views
10

有没有一种很好的方法来完成将选定元素过滤到几个类?我知道我可以一次完成一个,但这似乎是jQuery允许的。jQuery:多个类的过滤器

这些都是用ajax提供的,我没有权限定义实际的html。

$('.val>td').each(function() { 
    $(this).filter('.price,.quantity,.remove').children().children().addClass('hidetaxfields'); 
}); 
+0

将类直接添加到您的税务字段不是更容易吗,所以您可以轻松选择它们以便隐藏? – 2013-02-27 01:23:44

+0

我很困惑,你问是否可以在'.filter()'中使用''.price,.quantity,.remove''?由于'.filter()'带有一个jQuery选择器,因此您可以使用逗号来分隔多个选择标准。这是“多选择器”:http://api.jquery.com/multiple-selector/ – ajp15243 2013-02-27 01:24:08

+0

是的,这是我尝试的场景。它只是没有工作。 – 2013-02-27 01:27:07

回答

19

你所要求的心不是清楚从前mple你给...

这将产生由具有类的inital选择相匹配的元素的子集one OR two

$(selector).filter('.one, .two'); 

这将产生由inital匹配的元素的子集选择有两个类onetwo

$(selector).filter('.one.two'); 
+0

第一个是我的目标。我想知道为什么它不起作用? – 2013-02-27 01:33:02

+0

缺失的空间? – 2013-02-27 01:33:47

+0

白色空间在那里无关紧要。 – 2013-02-27 01:34:40

1

使用.is()方法应该工作:

$('.val>td').each(function() { 
    var $this = $(this); 
    if($this.is('.price, .quantity, .remove')){ 
     $this.children().children().addClass('hidetaxfields'); 
    } 
}); 

但是,这是更好:

$('.val>td.price, .val>td.quantity, .val>td.remove').each(function() { 
    $(this).children().children().addClass('hidetaxfields'); 
}); 

或本:

var $tds = $('.val>td').filter('.price, .quantity, .remove'); 
$tds.each(function() { 
    $(this).children().children().addClass('hidetaxfields'); 
}); 
2

带过滤器,你可以写一个过滤功能可以做到这一点,像这样(demo):

$('.val>td').filter(function() { 
    var that = $(this); 
    return that.hasClass('price') || that.hasClass('remove') || that.hasClass('quantity'); 
}).addClass('hidetaxfields'); 
+0

v方便,谢谢! – ptim 2013-10-17 04:56:58