2012-01-06 87 views
-3

我正在研究一個小插件,它檢查幾個輸入是否具有相同的值。我認爲最好的方法是將值存儲在一個數組中,並檢查這些值是否是唯一的,還是有更好的方法來做到這一點?JS:如何將數組中的值存儲在循環(每個)中並對其進行比較?

//想法

$('input').each(function(){ 
    var type = $(this).attr('class');//can be a other attribute 
    switch(type){ 
     case: 'red': 
     // some code 
     break; 

     case: 'green': 
     // some code 
     break; 

     case: 'black': 
     // the code to see if all inputs with the class black 
     //if they have the same value return in true or false, if all of the values 
     // are empty it should return false 
     break; 

     // more cases.... 
    }; 
}); 
+1

如果你想檢查輸入的*值*,爲什麼你的代碼看着「class」屬性?等一下;你想通過類來檢查類似的值......那麼,這將是一個非常脆弱的事情,因爲一個元素可以有多個「class」值;或者更恰當地說,「類」在語義上是一個*值列表*。 – Pointy 2012-01-06 14:39:55

+1

「返回真假」是什麼意思? – Blazemonger 2012-01-06 14:40:08

+0

這些輸入可以返回的數據類型是什麼? – 2012-01-06 14:43:05

回答

0

我會用一個對象吧:

var values = {}; 
var dupFound = false; 
$(...).each(function() { 
    var value = $(this).val(); 
    if(values[value]) { 
     dupFound = true; 
    } 
    else { 
     values[value] = this; 
    } 
}); 

這樣做的好處是,你可以輕鬆地訪問包含該值的其他元素。

+0

感謝您的快速幫助! – user759235 2012-01-06 14:59:39

0
function checkMatchingValues(cssClass) { 
    var value, matching = true; 
    $('input#' + cssClass).each(function() { 
     if(value == undefined) {value = this.val(); return} 
     if(value != this.var()) {matching = false; return} 
    } 
    return matching; 
} 
+0

謝謝,我會檢查一下! – user759235 2012-01-06 14:59:14

相關問題