如何仅显示符合所有复选框条件的div?

时间:2018-09-28 14:22:09

标签: jquery html

在下面的示例中,如果单击“ magazine”,则会出现两个“ magazine” div,这很好!

但是,当您单击“ $ 19.50”时,仍然会出现两个“杂志” div,但是现在每个带有“ 19”的div都会出现。

通过单击“ Magazine”和“ $ 19.50”,最终结果应该是单个“ Magazine 19” div,如果可以的话。谢谢!

$(":checkbox").click(function() {
    var re = new RegExp($(":checkbox:checked").map(function() {
        return this.value;
    }).get().join("|"));
    $(".product").each(function() {
        var $this = $(this);
        $this[re.source != "" && re.test($this.attr("class")) ? "show" : "hide"]();
    });
});
#product {
  margin-top:40px;
}
.product {
  background:#ebeef2;
  padding:10px;
  box-sizing:border-box;
  margin-bottom:10px;
  width:50%;
}
.filter-item {
  margin-right:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter-category">
    <h2>Filter By Price</h2>
    <label for="filter-price" class="filter-item">$19.50
        <input type="checkbox" value="nineTeen" id="filter-price">
        <span class="checkmark"></span>
    </label>
    <label for="filter-price" class="filter-item">$24.50
        <input type="checkbox" value="twentyFour" id="filter-price">
        <span class="checkmark"></span>
    </label>
</div>

<div class="filter-category">
    <h2>Filter By Type</h2>
    <label for="filter-type" class="filter-item">Blog
        <input type="checkbox" value="blog" id="filter-type">
        <span class="checkmark"></span>
    </label>
    <label for="filter-type" class="filter-item">Business
        <input type="checkbox" value="business" id="filter-type">
        <span class="checkmark"></span>
    </label>
    <label for="filter-type" class="filter-item">Education
        <input type="checkbox" value="education" id="filter-type">
        <span class="checkmark"></span>
    </label>
    <label for="filter-type" class="filter-item">Magazine
        <input type="checkbox" value="magazine" id="filter-type">
        <span class="checkmark"></span>
    </label>
    <label for="filter-type" class="filter-item">Profile
        <input type="checkbox" value="profile" id="filter-type">
        <span class="checkmark"></span>
    </label>
</div>

<div id="product">
    <div class="product education twentyFour">Education 24</div>
    <div class="product blog twentyFour">Blog 24</div>
    <div class="product business twentyFour">Business 24</div>
    <div class="product blog twentyFour">Blog 24</div>
    <div class="product business nineTeen">Business 19</div>
    <div class="product magazine nineTeen">Magazine 19</div>
    <div class="product magazine twentyFour">Magazine 24</div>
    <div class="product profile nineTeen">Profile 19</div>
    <div class="product blog twentyFour">Blog 24</div>
</div>

1 个答案:

答案 0 :(得分:0)

您在正则表达式中使用OR运算,因此如果存在至少一个值,则它匹配。即使将.join("|")更改为.join(" "),它也不会起作用,因为第一个复选框是针对价格的,并且产品列表中的类也不以此开头。

您应该保留用于生成正则表达式的类数组,并使用它来验证产品class中是否存在其中的所有值。 这可能会帮助您:JQuery hasClass