簡體   English   中英

帶有類別的jQuery復選框過濾器

[英]jquery checkbox filter with categories

我正在創建與此jsfiddle演示中類似的過濾器: http : //jsfiddle.net/nJUb3/1/

當您在此小提琴示例中選中紅色和黃色時,它顯示包含它們的花朵。 我試圖將其更改為以紅色或黃色顯示所有花朵。 它要么返回到此狀態,要么更改為在僅檢查紅色時僅顯示紅色的花朵或僅顯示黃色時顯示紅色的花朵的位置(並且在選中黃色時也將紅色和紅色選中則忘記了紅色)。

$('.flowers-wrap,.planets-wrap').delegate('input[type=checkbox]', 'change', function() {
    var $lis = $('.flowers > div'),
        $checked = $('input:checked');
    if ($checked.length) {
        var selector = '';
        $($checked).each(function(index, element) {
            selector += "[data-category~='" + element.id + "']";
            alert(selector);
        });
        $lis.hide();
        $('.flowers > div').filter(selector).show();
    } else {
        $lis.show();
    }
});

我想要的是(red or yellow) and (small,med,large) and (mars, venus) 如何更改這個小提琴示例以使其按我的意願工作? 謝謝。

當您遍歷所有選中的元素時,不需要創建一個選擇器,只需使用每個選中的復選框的element.id即可顯示它。 像這樣的東西:

$('.flowers-wrap,.planets-wrap').delegate('input[type=checkbox]', 'change', function() {
    var $lis = $('.flowers > div'),
        $checked = $('input:checked');  
    if ($checked.length) {  
        $lis.hide(); 
        $($checked).each(function(index, element) {                     
            $("[data-category~='" + element.id + "']").show();                            
        });                                              
    } else {
        $lis.show();
    }
});

您要做的就是將selector變量聲明更改為一個空數組而不是一個空字符串,然后遍歷其內容過濾的每個項目:

$('.flowers-wrap,.planets-wrap').delegate('input[type=checkbox]', 'change', function() {
  var $lis = $('.flowers > div'),
      $checked = $('input:checked');    
  if ($checked.length)
  {                         
    var selectors = [];//declare empty array named selectorS
    $($checked).each(function(index, element){                            
      selectors.push("[data-category~='" + element.id + "']");                            
    });                        
    $lis.hide();         
    selectors.forEach(function(selector){//iterate over elements
      $('.flowers > div').filter(selector).show();  
    })

  }
  else
  {
    $lis.show();
  }
});     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM