我有三个div。当页面loads.After单击按钮时,只有第一个div可见,第二个div变为可见。再次单击后,第三个div应该也会变得可见,但它没有,我也不明白为什么。
我通过一个检查div是否已经可见的js "if语句“来改变div的显示。
我做错了什么吗?
function displayMore() {
if (document.getElementById("div_02").style.display == "none") {
document.getElementById("div_02").style.display = "block";
} else if (document.getElementById("div_03").style.display == "none") {
document.getElementById("div_03").style.display = "block";
}
}#div_01 {
width: 100%;
height: 50px;
background: purple;
}
#div_02 {
display: none;
width: 100%;
height: 50px;
background: violet;
}
#div_03 {
display: none;
width: 100%;
height: 50px;
background: pink;
}<div id="div_01"></div>
<div id="div_02"></div>
<div id="div_03"></div>
<input type="button" onclick="displayMore();" value="Display More">
发布于 2021-02-03 21:43:23
这是一个使用计数器变量的解决方案。当你添加一个新的div然后增加你的计数器时,计数器代表你当前的div。可以使用nextElementSibling设置下一个元素的样式。
let counter = 0;
function displayMore() {
let currentDiv = document.getElementsByTagName("div")[counter];
console.log(currentDiv.nextElementSibling.style.display)
currentDiv.nextElementSibling.style.display = "block";
counter++;
}#div_01 {
width: 100%;
height: 50px;
background: purple;
}
#div_02 {
display: none;
width: 100%;
height: 50px;
background: violet;
}
#div_03 {
display: none;
width: 100%;
height: 50px;
background: pink;
}<div id="div_01"></div>
<div id="div_02"></div>
<div id="div_03"></div>
<input type="button" onclick="displayMore();" value="Display More">
https://stackoverflow.com/questions/66028630
复制相似问题