如何仅显示满足所有复选框条件的 div?



在下面的示例中,如果您单击"杂志",则会出现两个"杂志"div,这很好!

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

通过同时单击"杂志"和"19.50 美元",最终结果应该是单个"杂志 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>

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

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

最新更新