jQuery Filter DIV按类分为两个事件

时间:2018-03-29 23:52:20

标签: javascript jquery filter

我正在尝试设置一个过滤器,它将使用输入并选择定位结果。

HTML

<input type="search" id="filter-criteria">
<select id="filter-select">
  <option value="all">all</option>
  <option value="red">red</option>
  <option value="blue">blue</option>
  <option value="purple">purple</option>
</select>
<div class="red one girrafe item">Red One Girrafe</div>
<div class="blue two monkey item">Blue Two Monkey</div>
<div class="purple three gorilla item">Purple Three Gorilla</div>
<div class="red three girrafe item">Red Three Girrafe</div>
<div class="green three gorilla item" style="display: none">Purple Three Gorilla</div>

JS

jQuery(document).ready(function() {
    $('#filter-criteria').add('#filter-select').on('keyup change', function() {
        $('.item').hide();
        var txt = $('#filter-criteria').val();
        var select = $('#filter-select').val();

        if (select == "all" && txt == "") {
            $('.item').show();
        } else {
            $('.item').each(function() {
                if ($(this).is('[class*=' + txt + ']' && '[class*=' + select + ']')) {
                    $(this).show();
                }
            });
        }

    });
});

目前只有选择输入有效。

https://codepen.io/andew_taylor/full/OvvMLR

1 个答案:

答案 0 :(得分:0)

$('#filter-criteria').add('#filter-select').on('keyup change', function() {
    $('.item').hide();
    var txt = $('#filter-criteria').val();
    var select = $('#filter-select').val();
       
    select = select == "all" ? "item" : select;
    txt = txt == "" ? "item" : txt;
    $('.item').each(function() {
        var $this = $(this)
        if ($this.is('[class*=' + txt + ']') && $this.is('[class*=' + select + ']')) {
            $this.show();
        }
    });
});
.item{
    display: inline-block;
    width:100px;
    height: 100px;
}
.red{
    background-color: red;
}
.blue{
    background-color: blue;
}
.purple{
    background-color: purple;
}
.green{
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="filter-criteria">
<select id="filter-select">
    <option value="all">all</option>
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="purple">purple</option>
</select>
<div class="red one girrafe item">Red One Girrafe</div>
<div class="blue two monkey item">Blue Two Monkey</div>
<div class="purple three gorilla item">Purple Three Gorilla</div>
<div class="red three girrafe item">Red Three Girrafe</div>
<div class="green three gorilla item" style="display: none">Purple Three Gorilla</div>

你找不到任何.item类“全部”或类“”

您可以更改选择的值或制作其他条件

btw,<div class="green three gorilla item" style="display: none">Purple Three Gorilla</div>

我猜第一堂课应该是紫色的