色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

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

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

如果我的隱藏元素(下拉列表)在單擊父元素時(shí)打開,在這種情況下,我如何通過單擊另一個(gè)父元素來關(guān)閉它們?這是我在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);
    });
  }
});

作為一個(gè)解決方案,我嘗試了這個(gè)選項(xiàng),但它不起作用

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>