gpt4 book ai didi

javascript - 通过复选框过滤 div

转载 作者:行者123 更新时间:2023-11-28 04:16:26 24 4
gpt4 key购买 nike

我有一个复选框。我需要通过选择它们来过滤。

<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india"/>India</label>
</div>
</div>

应该过滤的div下面

<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan</h2>
</div>
</div>

在我的脚本下面。但我不能取复选框的值。我应该怎么做。除了很多if之外还有其他方法吗?

 <script>
var choose = document.getElementsByClassName('chechbox');
const div = document.getElementsByClassName('result');
if (choose.value){
result.style.display = "block";
}
</script>

请帮我写脚本

最佳答案

choosediv 都是元素列表,而不是单个元素。您需要迭代它们。

    var checkboxes = document.getElementsByClassName('checkbox'); 
Array.from( checkboxes ).forEach( function( checkBox ){
///rest of the code
})

演示

var checkboxes = document.querySelectorAll('[type="checkbox"]');

var fnDisplayDivs = () => {
Array.from(checkboxes).forEach(function(checkBox) {
var div = document.querySelector("." + checkBox.getAttribute("rel"));
if (checkBox.checked) {
div.style.display = "block";
} else {
div.style.display = "none";
}
})
};

Array.from(checkboxes).forEach(function(checkBox) {
checkBox.addEventListener( "change", function(){
fnDisplayDivs();
})
});
fnDisplayDivs();
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india"/>India</label>
</div>
</div>

<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan</h2>
</div>
</div>

关于javascript - 通过复选框过滤 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48300164/

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