2011-06-09 31 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'])){ 

}