我正在尝试创建一个功能,当您单击一个按钮时,它会删除一个 div,并添加另一个 div,然后当您再次按下该按钮时,它将删除该 div 和另一个 div。这大约进行了 4 次,直到我到达终点,然后当我再次按下按钮时,它应该回到开头。我究竟做错了什么?
let switchData = (selected, removed1, removed2, removed3) => {
if(!document.getElementById("show-next-data")) {
return;
}
document.getElementById("show-next-data").addEventListener("click", ()=> {
let infoData = [selected, removed1, removed2, removed3];
document.getElementById(selected).style.display = "block";
/*for (let i = 0; i < infoData.length; i++) {
document.getElementById(infoData[i]).style.display = "none";
}*/
document.getElementById(removed1).style.display = "none";
document.getElementById(removed2).style.display = "none";
document.getElementById(removed3).style.display = "none";
});
}
switchData("dog-care", "cat-care", "youtube-media", "table-data");
switchData("cat-care", "dog-care", "youtube-media", "table-data");
switchData("youtube-media", "cat-care", "dog-care", "table-data");
switchData("table-data", "cat-care", "youtube-media", "dog-care");
<div id="info-content">
<div id="dog-care">
<h1 id="animal-info">How To Take Care Of My Dog:</h1>
<h4 id="animal-info">Make sure your dog is well fed
</h4>
</div>
<div id="cat-care">
<h1 id="animal-info">How To Take Care Of My Cat:</h1>
<h4 id="animal-info">Make sure your cat is well fed
</h4>
</div>
<div id="youtube-media">
<iframe width="200%" height="300%" src="https://www.youtube.com/embed/Yzv0gXqoCkc" title="YouTube video player"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" ></iframe>
</div>
<div id="table-data">
<h1>table goes here</h1>
</div>
<h1 id="show-next-data">︾</h1>
</div>
少写多做,让你的生活更轻松:
const divs = document.querySelectorAll("#info-content>div");
var idx=0;
divs.forEach(nextDiv); // step through all divs once to hide them all but the first ...
document.getElementById("show-next-data").onclick=nextDiv;
function nextDiv(){
divs[idx].style.display="none";
divs[idx=(idx+1)%divs.length].style.display="";
};
<div id="info-content">
<div id="dog-care">
<h1 id="animal-info">How To Take Care Of My Dog:</h1>
<h4 id="animal-info">Make sure your dog is well fed
</h4>
</div>
<div id="cat-care">
<h1 id="animal-info">How To Take Care Of My Cat:</h1>
<h4 id="animal-info">Make sure your cat is well fed
</h4>
</div>
<div id="youtube-media">
<iframe width="200%" height="300%" src="https://www.youtube.com/embed/Yzv0gXqoCkc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe>
</div>
<div id="table-data">
<h1>A table goes here</h1>
</div>
<button id="show-next-data">︾</button>
</div>
该函数nextDiv()
显示下一个div
从idx
(集合中的索引号divs
(通过选择器找到#info-content>div
)开始。当前的 div 被隐藏,idx 增加,并且通过将其.style.display
属性重置为""
(一个空字符串)来显示下一个 div。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句