2014-01-08 57 views
1

我有一個頁面上的鏈接列表和一組複選框應該過濾鏈接,以便只有那些具有特定條件的鏈接將被激活。我這樣做的初步嘗試涉及創建一個活動的所有過濾器選項的數組,並運行.filter(Array)以使這些活動處於活動狀態,並使用.not(Array)禁用其他鏈接。使用jquery過濾器作爲過濾頁面上的鏈接的方式

問題是,如果選擇了多個過濾器選項,則與任一過濾器選項匹配的任何鏈接都將處於活動狀態。實際上,我想要的只是匹配所有過濾器選項的鏈接處於活動狀態。

這裏是我的精簡版在jsFiddle

var filterAll = ["filter-F_0", "filter-F_1", "filter-F_2", "filter-F_3", "filter-F_4", "filter-P_0", "filter-P_1", "filter-P_2", "filter-P_3", ] 
var filterActive = []; 

function filterApps(){ 
if(filterActive.length == 0) 
{ 
    filterReset(); 
    return; 
} 

var arrActive = $.map(filterActive, function (val) { 
                 return '[' + val + ']' 
                }).join(",") 

addToLog("arr = " + arrActive); 

$(".appLink").filter(arrActive).css(activeAppCSS).addClass("active").removeClass("disable"); 


$(".appLink").not(arrActive).css(disabledAPPCSS).addClass("disable").removeClass("active");} 
+0

_「代替這是這個標準,只有符合這些標準的標準纔會被激活。「_你能更具體一些嗎? – undefined

+0

當前如果您選擇多個過濾器選項,則與任一過濾器選項相匹配的任何內容都將處於活動狀態。實際上,我想要的只是與兩個篩選器選項都匹配的鏈接處於活動狀態。 *更有意義*? – Bardsworth

+0

我編輯我的帖子要清楚一點。 (我希望) – Bardsworth

回答

0

這裏,使用屬性的名稱,過濾元件是一個可怕的想法(對不起)存在複雜的東西,你可以使用data-*屬性那家商店數組中的過濾標準。如果我已經正確地理解了這個問題,這個解決方案應該可以工作,這個解決方案使用attributes屬性讀取屬性的名字,應該注意它不是執行該任務的最有效的方式,並且因爲Array對象的.filter()方法被使用,它不會在不支持ES5的舊版瀏覽器中工作,爲支持這些瀏覽器,您可以使用shim

var $links = $('.appLink'); 
var $checkboxes = $('input[type=checkbox]').on('change', function() { 
    // Creating an array of values 
    var checked = $checkboxes.filter(':checked').map(function() { 
     return this.value.toLowerCase(); 
    }).get(); 

    // Filtering the .appLink elements by reading the attributes 
    // and comparing the filtered array's length with the checked one 
    $links.removeClass('matched').filter(function() { 
     return [].slice.call(this.attributes).filter(function (a) { 
      return a.name.indexOf('filter') === 0; 
     }).filter(function(f) { 
      return $.inArray(f.name.replace('filter-', ''), checked) > -1; 
     }).length === checked.length; 
    }).addClass('matched'); 

}); 

http://jsfiddle.net/85tTp/

在要使用data-*性能的情況下,你可以定義屬性像data-filter='["f1", "f2", ""]'的元素和使用jQuery .data()方法讀取它們:

$links.removeClass('matched').filter(function() { 
    return $(this).data('filter').filter(function(f) { 
     return $.inArray(f, checked) > -1; 
    }).length === checked.length; 
}).addClass('matched');