选中复选框以筛选与所有选择匹配的结果

时间:2015-06-11 20:10:56

标签: javascript jquery html css

我有3个复选框可以在结果之间切换。它按原样工作,但是,我希望能够同时使用多个复选框进行过滤。

例如,如果勾选了highbread,则只应显示一个结果,因为它只与divs中的一个匹配。目前它显示的内容为highbread

https://jsfiddle.net/f7srx0dd/12/

<input type="checkbox" class="checkbox" name="High" data-category-type="high">High
<input type="checkbox" class="checkbox" name="low" data-category-type="low" > 
<input type="checkbox" class="checkbox" name="low" data-category-name="bread" > 

<div id="Categories">
    <div class="hide" data-category-type="high" data-category-name="pizza">high</div>
    <div class="hide" data-category-type="low" data-category-name="pasta">low</div>
    <div class="hide" data-category-type="low" data-category-name="pizza">low</div>
    <div class="hide" data-category-type="high" data-category-name="bread">bread</div>
</div>

$('.checkbox ').on('click', function (e) {



var $this = $(this),
    $links = $('.checkbox');

if ($this.hasClass('selected')) {
    $this.removeClass('selected');
} else {
    $this.addClass('selected');
}

$('#Categories > div').hide();
var anySelectedCheckbox = false;
$.each($links, function (k, v) {

    $this = $(v);

    if ($this.hasClass('selected')) {
        anySelectedCheckbox = true;
        var cat = $this.data('categoryType');
        var nam = $this.data('categoryName');
        $('#Categories > div[data-category-type="'+cat+'"]').show();
        $('#Categories > div[data-category-name="'+nam+'"]').show();
    }

});

if(!anySelectedCheckbox) {
$('#Categories > div').show();

}


});

1 个答案:

答案 0 :(得分:4)

我会通过保持一个与复选框匹配的运行过滤器来实现此目的。首先选择所有结果作为jQuery对象。然后,对于每个复选框,过滤jQuery对象以仅匹配那些特定的:

var selectedDivs = $('#Categories > div').hide();
var anySelectedCheckbox = false;
$.each($links, function (k, v) {

    $this = $(v);

    if ($this.hasClass('selected')) {
        anySelectedCheckbox = true;
        var cat = $this.data('categoryType');
        var nam = $this.data('categoryName');
        selectedDivs = selectedDivs.filter('[data-category-type="'+cat+'"], [data-category-name="'+nam+'"]');
    }

});
selectedDivs.show();