如何使用jQuery按多个条件正确筛选列表

How to properly filter a list by multiple criteria with jQuery?

本文关键字:筛选 列表 条件 何使用 jQuery      更新时间:2023-09-26

我想对我的DOM执行以下操作:

通过多个控件(组合(过滤列表:

  • 复选框
  • 选择框
  • 自由文本输入(例如http://vdw.github.io/HideSeek/)

    例如,用户可以从选择框中选择一个城市,该框会过滤显示的项目。当在输入字段中键入时,select中的筛选器仍然存在,从而根据输入的文本进一步筛选显示的项目。

我通常会手写一些东西,将不同选择框中的多个选项组合在一起,但这并不理想。此外,对于"自由文本"过滤器,我一直使用jQuery插件,当你开始打字时,它们往往会重置选择。

对于表,我使用datatables插件,它带来了多个过滤器。它的功能非常丰富,但也很重,而且是为表设计的,而不是为任何类型的列表设计的。

关于如何实现这一目标,有哪些一般性建议/大纲?

附言:这是我现在的做法。a( 它是非常专有的,b(我还没有设法将它与文本过滤器结合起来:

function showItems(selectedCanton,showTypeOne,showTypeTwo){
    var typeOneSelector = '';
    var typeTwoSelector = '';
    if (selectedCanton=='all'){
        var cantonSelector = '';
    }
    else {
        var cantonSelector = '.list-item[data-canton="'+selectedCanton+'"]';
    }
    if (showTypeOne){
        if (showTypeTwo){
            selector = cantonSelector;
            //selector = cantonSelector+'[data-type="one"],'+cantonSelector+'[data-type="two"]';
        }
        else {
            selector = cantonSelector+'[data-type="one"]';
        }
    }
    else if (showTypeTwo){
        selector = cantonSelector+'[data-type="two"]';
    }
    $('.list-item').hide();
    console.log(selector);
    $(selector).show(); 
}
$(document).ready(function($){
        $(".filter-select").change(function() {     
            var selectedCanton = $("#canton").val(); 
            var showTypeOne = $("#type-one").prop('checked');
            var showTypeTwo = $("#type-two").prop('checked'); 
            showItems(selectedCanton,showTypeOne,showTypeTwo);
        });
});

您可以使用jquery的过滤功能。

试试

$('.list-item').hide();
$('.list-item').filter(function (index, e) {
    var condition = true;
    var el = $(e);
    if(showTypeOne)
    {
      condition = condition && (el.data("type") === "one");
    }
    if(showTypeTwo)
    {
        condition = condition && (el.data("type") === "two");
    }
    if(selectedCanton!='all')
    {
        condition = condition && (el.data("canton") === selectedCanton);
    }
    return condition;
 })
.show();

你可以通过这种方式添加文本过滤器。。

工作样品:http://jsfiddle.net/CufMp/1/