简体   繁体   English

用于多个 Div 类元素的 Javascript OnClick 函数,单击时显示文本块

[英]Javascript OnClick function for multiple Div Class elements that reveal a block of text when clicked on

I am trying to enable an Onclick event to fire up when any of my div elements that match the div class "Clicker" is clicked on.我试图在单击与 div 类“Clicker”匹配的任何 div 元素时启用 Onclick 事件。 However iI am not so good with JavaScript and do not know how to go about this.但是我对 JavaScript 不太好,不知道如何去做。 I was successful when I used the "document.getElementById" when my divs were made into Id and not "Class" elements but only one could function.当我的 div 被制作成 Id 而不是“Class”元素但只有一个可以运行时,当我使用“document.getElementById”时,我成功了。 see my code below;请参阅下面的代码;

 document.getElementsByClassName("Clicker").addEventListener("click", function () { var infoBox = document.getElementsByClassName("thumbnail-reveal-txt"); if (infoBox.style.display == "none") { infoBox.style.display = "block"; } else { infoBox.style.display = "none"; } })
 <div class="thumbnail-reveal-txt" style="position: absolute; display: none;"> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;"> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">

You can use querySelector and querySelectorAll您可以使用querySelectorquerySelectorAll

 document.querySelector(".Clicker").addEventListener("click", function () { const infoBox = document.querySelectorAll(".thumbnail-reveal-txt"); infoBox.forEach(i => { if (i.style.display == "none") { i.style.display = "block"; } else { i.style.display = "none"; } }) })
 <button class="Clicker">click</button> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">1</div> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">2</div> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">3</div>

When you use getElementsByClassName, you're not specifying wich of the elements you are trying to change the className property.当您使用 getElementsByClassName 时,您没有指定要更改 className 属性的元素。

For that, you can use a loop为此,您可以使用循环

document.getElementsByClassName("Clicker").addEventListener("click", function () {
  var infoBox = document.getElementsByClassName("thumbnail-reveal-txt");

for (let i = 0; i < infoBox.length; i +=1) {

if (infoBox[i].style.display == "none") {
    infoBox[i].style.display = "block";
  } else {
    infoBox[i].style.display = "none";
  }

}
 


})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM