2011-06-09 33 views
5

很容易做循环,但我想知道是否有一种方法来查看集合中的每个项目是否匹配没有循环的条件。例如:jquery测试一个条件与整个集合没有循环

if($('.many-items-of-this-class').hasClass('some-other-class')) { } 

如果集合中的任何项返回true,则返回true。有没有办法做这种操作,所以只有当所有项都为真时才返回true?

回答

5

您可以缓存该设置,然后针对测试其他类的设备运行过滤器,并比较两者的属性。

var many_items = $('.many-items-of-this-class'); 

if(many_items.length === many_items.filter('.some-other-class').length) { } 

或更短,但可以说较为混乱,你可以使用一个.not()滤波器.length!

var many_items = $('.many-items-of-this-class'); 

if(!many_items.not('.some-other-class').length) { } 
+1

德勤与过滤,脑屁了一会儿。 - 编辑:正在思考'地图',然后使用'上下文'。我从来没有想过过滤器存在! ; p – 2011-06-09 17:40:18

0
var $many = $('.many-items-of-this-class'); 
if (many.filter('.some-other-class').length == $many.length) 
{ 
    // all items have the class. 
} 

也许?其他选项是自己制作Selector。例如

.many-items-of-this-class:and(.some-other-class) 

什么的。

+0

您可以使用两个类选择器:'$('。many.some')' – js1568 2011-06-09 17:41:37

+0

@ js1568:我很清楚,但我收到的印象是确保每个'.many-items这个类的项目,它**必须**也有'.some-other-class'应用于它(换句话说,不仅是两个在场的项目) – 2011-06-09 17:43:19

+0

好点,我有更多的与你的“和”选择器挂断。也许它会更好地标记为“isAlways” – js1568 2011-06-09 17:47:34

0

检查它的目标是什么?如果您正在执行的操作,那么你可以通过chaining the selector检查这两个班在一次:

$('.many-items-of-this-class.some-other-class').each(
    function(index, value) { 
     // Do stuff here 
    }); 
+0

这并不比较(或检查)与_class A_ **所有项目也**已应用_class B_。 – 2011-06-09 17:41:59

+0

@Brad:它没有--jQuery选择器检索同时应用了类A和类B的所有项目。当然,如果您需要检查所有_class A_是否仅仅为了检查而应用_class B_,那么是的,这不是最好的方法。 – voithos 2011-06-09 17:45:08

+1

我把它作为后面的任务来读取(确保每个带有_class A_的项目都有一个_class B_应用于它(不仅仅是相交的项目)。 – 2011-06-09 17:47:20

0
if(! $('.many-items-of-this-class').is(':not(.some-other-class)')) { } 

或者,如果集合是基于一个选择,只需

if($('.many-items-of-this-class:not(some-other-class)').length == 0) { } 
0
if($('.many-items-of-this-class :not(.some-other-class)').size() == 0) { 
    // ... 
} 
1

您可以轻松编写一个插件来扩展每个功能。

(function($){ 
    $.fn.allMustPassTest = function(test,params) { 
     var allPass = true; 
     $(this).each(function(){ 
      if(!test.apply($(this),params)){ 
       allPass = false; 
      } 
     }); 
     return allPass; 
    }; 
})(jQuery); 

与应用,例如:

var allPass = $('.many-items-of-this-class').allMustPassTest(function(){ 
    return $(this).hasClass('some-other-class'); 
}); 
if(allPass){ 
    //code to execute if all items have .some-other-class 

} 

或者另一种方式:

var hasClassTest = function(clazz){ 
    return $(this).hasClass(clazz); 
}; 
if($('.many-items-of-this-class').allMustPassTest(hasClassTest,['some-other-class'])){ 

}