首页 > 解决方案 > Why does my script only act on the first element with a particular ID value?

问题描述

I have a query that produces a number of DIV id="toggle_panel" I know I can effectively change the ID of the DIV dynamically.

Below is the script, straight from w3schools, which works great out of the box...for the first DIV and first DIV only. How do I apply a dynamic variable from the query to my script?

Second question: How do I get it so the DIV are hidden by default?

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

Thank you

标签: javascripthtmltogglevisibility

解决方案


对于您的第一个问题,使用类来标记类似 html 元素的集合更合适。

所以你的 div 应该是这样的:

<div class="toggle_panel">...</div>
<div class="toggle_panel">...</div>
<div class="toggle_panel">...</div>

然后,您可以使用document.getElementsByClassName('toggle_panel')它们来访问它们。

同样要默认隐藏它们,您可以使用 css 来定位您的类,如下所示。

.toggle_panel {
   display: none;
}

推荐阅读