欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

我如何使用js來切換基于按鈕點擊的元素的可見性?

錢良釵1年前9瀏覽0評論

如果我的隱藏元素(下拉列表)在單擊父元素時打開,在這種情況下,我如何通過單擊另一個父元素來關閉它們?這是我在js中的代碼

function toggleElement(elementId) {
  var element = document.querySelector(elementId);
  element.style.display = element.style.display === "none" ? "block" : "none";
}

document.addEventListener("DOMContentLoaded", function() {
  var buttons = document.getElementsByClassName("ContainerForMenu");
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function() {
      var target = this.getAttribute("data-target");
      toggleElement(target);
    });
  }
});

作為一個解決方案,我嘗試了這個選項,但它不起作用

function toggleElement(elementId) {
  var elements = document.querySelectorAll('.child-element');
  
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = "none";
  }
  
  var element = document.querySelector(elementId);
  element.style.display = "block";
}

document.addEventListener("DOMContentLoaded", function() {
  var buttons = document.getElementsByClassName("ContainerForMenu");
  
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function() {
      var target = this.getAttribute("data-target");
      toggleElement(target);
    });
  }
});

跟隨我的代碼您可以使用toggle基于按鈕單擊來切換元素的可見性...

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>