我正在尝试创建一个带有复选框的过滤器,当有人点击复选框时会隐藏所有div1
//so far i have used
function div1hide() {
document.getElementById("dive1").style.display ='none';
}
var hider = document.getElementById("div1");
document.addEventListener("click", dive1hide, false);

< id="div1">test</div>
< id="div1">test</div>
< id="div1">test</div>
< id="div1">test</div>
&#13;
它只隐藏了第一个我不知道为什么它没有隐藏所有其他的......
答案 0 :(得分:2)
这样的事可能吗?
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<input type="checkbox" id="hider" />
<script>
var div1 = document.getElementsByClassName("div1"); // divs to control
var hider = document.getElementById("hider"); // checkbox
div1.toggleStatus = "on"; // let's go!
hider.onclick = function(){ // what happen when hitting the checkbox
switch(div1.toggleStatus){ // two options
case "on": // 1: hide it!
div1.toggleStatus="off"; // hit the checkbox again and jump to 2nd option
for (i = 0; i < div1.length; i++) { // choose all elements
div1[i].style.display = "none"; // hide them
}
break;
case "off": // 1. show it!
div1.toggleStatus="on"; // hit the checkbox again and jump to 1st option
for (i = 0; i < div1.length; i++) { // choose all elements
div1[i].style.display = "block"; // show them
}
break;
}
}
</script>
答案 1 :(得分:0)
将此更改为更像这样。 getElementsByClassName
返回一个对象,然后可以迭代该对象以更改该选择中所有元素的显示。
function div1hide() {
var els = document.getElementsByClassName("div1");
for(const el in els){
els[el].style.display = "none";
}
}
var hider = document.getElementsByClassName("div1");
document.addEventListener("click", div1hide, false);
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
答案 2 :(得分:0)
function div1hide() {
var els = document.getElementsByClassName('div1');
for(var i = 0; i < els.length; i++){
els[i].style.display = 'none';
}
}
document.getElementById('hide').addEventListener('click', div1hide, false);
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div class="div1">test</div>
<div id="hide">Click to hide.</div>