2013-03-09 29 views
0

我有100行數據,每個數據有3個屬性:年齡,位置,性別。邏輯:結合下拉框切換可見性

我有3個選擇框,根據年齡,位置和性別來過濾我的數據。

我的函數setVisible(true)或setVisible(false)使行隱藏或可見。

我想過濾我的數據,具體取決於下拉框選擇的內容。

我已成立了3個事件監聽器:

$('.age_selector').change(function() { 
    for (i=0;i<data.length;i++){ 
     if (data[i].age == $('.age_selector').val()){ 
      data[i].setVisible(true); 
     } else { 
      data[i].setVisible(false); 
     } 
    } 
}); 
$('.location_selector').change(function() { 
    for (i=0;i<data.length;i++){ 
     if (data[i].location == $('.location_selector').val()){ 
      data[i].setVisible(true); 
     } else { 
      data[i].setVisible(false); 
     } 
    } 
}); 
$('.gender_selector').change(function() { 
    for (i=0;i<data.length;i++){ 
     if (data[i].gender == $('.gender_selector').val()){ 
      data[i].setVisible(true); 
     } else { 
      data[i].setVisible(false); 
     } 
    } 
}); 

我的問題是,能見度僅取決於我最近選擇的下拉選項。例如,如果我選擇美國爲位置,那麼我選擇男性,我的名單顯示全部男性,不管地點/年齡。我怎樣才能將邏輯結合起來,以便將其過濾以僅顯示美國男性?

感謝

編輯: 我希望有沿反線的東西,這樣反而具有

if (data[i].age == $('.age_selector').val()){ 
    data[i].setVisible(true); 
} 

我會像

if (data[i].age == $('.age_selector').val()){ 
    data[i].counter++; 
}else{ 
    data[i].counter--; 
} 

這在最後,如果計數器高於某個值,數據將是可見的。這可能嗎?

回答

0

我會做這樣的事情:

// Store our current selections 
var age_selection, location_selection, gender_selection; 

// Do the real filtering 
function do_filter() { 
    // For each element 
    for (i=0;i<data.length;i++) { 
     // If our data doesn't match one of the selections, set it to not visible 
     if (age_selection != null && data[i].age != age_selection) { 
      data[i].setVisible(false); 
     } else if (location_selection != null && data.location != location_selection) { 
      data[i].setVisible(false); 
     } else if (gender_selection != null && data.gender != gender_selection) { 
      data[i].setVisible(false); 
     } else { 
      // Otherwise, set it visible 
      data[i].setVisible(true); 
     } 
    } 
} 

// When one of the selectors changes, store the selection, and call do_filter 
$('.age_selector').change(function() { 
    age_selection = $('.age_selector').val(); 
    do_filter(); 
}); 
$('.location_selector').change(function() { 
    location_selection = $('.location_selector').val(); 
    do_filter(); 
}); 
$('.gender_selector').change(function() { 
    gender_selection = $('.gender_selector').val(); 
    do_filter(); 
});