2012-08-29 51 views
0

我正在嘗試構建一個基於多個屬性的非常簡單的過濾器系統。非常簡單的過濾系統?

在我的例子中,我用:

  • 性別
  • 身高

我想能夠之間的「男/女」和「短/高大的選擇」。因此,有四種可能的組合:

  • 男/短
  • 男/高大
  • 女/短
  • 女/高大

在只有兩個選擇的情況下,每個過濾器組,每次只能檢查一個過濾器組。

我遇到的問題是簡單的邏輯。現在,點擊「男人」會隱藏女人。但點擊「高」將只顯示「高」的人。

我只是想知道是否有一個優雅的解決方案來建立這個基本系統?

謝謝!

http://jsbin.com/ixokek/1

回答

1

你只關心當前的過濾器設置;你不考慮其他。如果有一個能夠讀取所有過濾器設置的通用過濾器函數以及僅僅交換活動狀態的點擊處理程序,那麼它可以說更加優雅:http://jsbin.com/ixokek/7/。爲什麼你把你的功能的變種內,而不是剛命名的功能,我

$('#filter li').click(function(){ 
    $(this).siblings().removeClass("active"); // remove active from other 
    $(this).toggleClass("active"); // toggle active on current 
    filter(); // filter elements 
}); 

var filter = function() { 
    // array of classes that items need to have 
    var classes = $("#filter li.active") 
     .map(function() { 
     return $(this).data("filter"); 
     }) 
     .toArray(); 

    $(".item").each(function() { 
    var $this = $(this); 

    // it should show if it has all classes as the settings say 
    var show = classes.every(function(aClass) { 
     return $this.hasClass(aClass); // class is a reserved word 
    }); 

    // toggle appropriately 
    if(show) { 
     $this.fadeIn(200); 
    } else { 
     $this.fadeOut(200); 
    } 
    }); 
}; 
+0

你能解釋一下嗎?像這樣:'function filter(){// something}' –

+0

@Bram Vanroy:我習慣於一種類型的函數,它是函數表達式。這些也是匿名函數。不過,函數聲明沒有錯。 – pimvdb

+0

精美的作品,謝謝! – waffl

1
$('#filter li').on('click', function(){ 
    $(this).toggleClass('active').siblings().removeClass('active'); 
    var gender = $('#filter ul').eq(0).find('.active').data('filter')||'', 
     height = $('#filter ul').eq(1).find('.active').data('filter')||'', 
     sel = '.item'+(gender!=''?'.'+gender:'')+(height!=''?'.'+height:''); 
    $(sel).fadeIn(200) 
    $('.item').not(sel).fadeOut(200); 
});​ 

FIDDLE

+0

也很好,謝謝! – waffl