jquery中的复杂过滤器

时间:2011-03-22 01:27:54

标签: php jquery filter

我有一个我正在显示的产品列表,我目前正在开发一个不使用ajax的过滤功能。

每个产品都根据其所属的类别附加了一系列类别。像这样:

<li class="f_all f_cat1 f_cat2">Product 1</li>
<li class="f_all f_cat1 f_cat3 f_cat_4">Product 2</li>
<li class="f_all f_cat4 f_cat5 f_cat6">Product 3</li>

这意味着许多产品属于同一类别。

这些是过滤器选项:

<table cellspacing="10">
  <tr>
    <td class="item" id="p_1">Category 1</td>
    <td class="item" id="p_2">Category 2</td>
    <td class="item" id="p_3">Category 3</td>
  </tr>
</table>

到目前为止,我有一个基本的过滤器,它允许我根据单个类别进行过滤,如下所示:

function filterProd(filter){
$(".f_all").hide(); // first hide all products
$(".f_"+filter).show();  // show products only for this category
}

然后点击功能:

$("#p_1").click(function(){filterProd("cat1");});
$("#p_2").click(function(){filterProd("cat2");});
$("#p_3").click(function(){filterProd("cat3");});

我知道这不是理想的做法,但我只是在寻找一点指导。

我想在此之后做两件事:

  • 单击此选项后,再次从功能
  • 中删除该过滤器
  • 单击其他选项时,将其添加到过滤器
  • 我假设一个接受一组值等的类的函数,但我对jquery相当新,并且会感谢我在这一点上得到的任何帮助。

    2 个答案:

    答案 0 :(得分:1)

    您需要类似全局变量的内容来列出所有当前已过滤的选项。所以我打算建议一个阵列,但这可能是也可能不是最适合你的。对于所有反对“booo,全局变量糟透了”的反对者,我要求你在这里评估用户的专业性,并考虑与答案的可用性保持一致的选项。

    var options = { 'cat1':false,'cat2':true,'cat3':false,'cat4':false,'cat5':false} //you can figure this out on your own.
    function GetFilterValues(){
      var returnFilter = '';
      for(key in options) {
        if (options[key]) { //this checks to see if the value is true
          returnFilter = returnFilter + '.f_' + key + ' ,';
        }
      }
      //remove the last comma
      if (returnFilter.substring(returnFilter.length - 1) == ',') returnFilter = returnFilter.substring( 0, returnFilter.length - 1 );
      return returnFilter;
    }
    

    然后只需在你的选择器中使用此功能:

    function filterProd(filter){
      $(".f_all").hide(); // first hide all products
      $(GetFilterValues()).show();  // show only selected categories.
    }
    

    要从列表中添加和删除过滤器选项,请尝试以下操作:

    function toggleOptionsValue(key){
      options[key] = !options[key];
    }
    

    答案 1 :(得分:1)

    一种选择是将过滤器存储在一个数组中:http://jsfiddle.net/4yWWH/

    编辑:修改为显示所有产品,如果没有过滤器则退出:http://jsfiddle.net/4yWWH/1/