gpt4 book ai didi

javascript - 使用类显示和隐藏 div

转载 作者:行者123 更新时间:2023-12-02 16:21:13 25 4
gpt4 key购买 nike

我编写了下面的脚本,在单击复选框时显示和隐藏 div。它获取复选框值,然后用该类隐藏 div。我的问题是一个 div 可能被标记有两个复选框值。如果仍然勾选其中一个,我仍然希望显示 div 而不是像我的脚本当前那样隐藏。解决方法是什么?

HTML

    <fieldset class="simple-filter">
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="bmx" value="bmx" checked>
<label for="bmx">BMX</label>
</div>
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="scooter" value="scooter" checked>
<label for="scooter">Scooter</label>
</div>
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="quad" value="quad" checked>
<label for="quad">Quad/Inline</label>
</div>
</fieldset>

<div class="simple-filter-items">
<div class="bmx scooter">box 1</div>
<div class="bmx">box 2</div>
<div class="quad">box 3</div>
</div>

脚本:

    jQuery(document).ready(function($){

$( ".filter-click" ).change(function() {

checkboxval = $(this).val();

$(".simple-filter-items").find("." + checkboxval).toggle();

});

});

fiddle 在这里 https://jsfiddle.net/h5as3cwb/

最佳答案

您可以使用 each 循环遍历 checked 复选框并显示复选框被选中的 div

演示代码:

jQuery(document).ready(function($) {
$(".filter-click").change(function() {
//hide all div
$(".simple-filter-items div").hide()
//loop throgh checked checkboxes
$(".simple-filter input[type=checkbox]:checked").each(function() {
//show them
$(".simple-filter-items").find("." + $(this).val()).show();
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="simple-filter">
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="bmx" value="bmx" checked>
<label for="bmx">BMX</label>
</div>
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="scooter" value="scooter" checked>
<label for="scooter">Scooter</label>
</div>
<div class="filter-wrap">
<input type="checkbox" class="filter-click" name="quad" value="quad" checked>
<label for="quad">Quad/Inline</label>
</div>
</fieldset>

<div class="simple-filter-items">

<div class="bmx scooter">box 1</div>
<div class="bmx">box 2</div>
<div class="quad">box 3</div>
</div>

关于javascript - 使用类显示和隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65410301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com