javascript - 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
解决方案
对于您的第一个问题,使用类来标记类似 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;
}
推荐阅读
- swift - 如何使用 RxSwift 和 Alamofire 使用分页?
- android - 模拟器:模拟器:错误:x86_64 仿真当前需要硬件加速
- django - uwsgi 处理请求的时间不能超过一分钟
- ansible - Ansible 循环/条件
- elasticsearch - 使用logstash从json中提取数字并发送到elasticsearch
- c# - Birds Eye View Bing Maps 不适用于 WPF 应用程序 C#
- aws-lambda - 基于 cookie 的两个源之间的 Lambda@Edge 路由
- php - 如何在 WordPress 中的作者存档页面下列出帖子?
- c# - RestSharp - 您的浏览器当前设置为阻止 cookie
- c# - 为什么在调用 lambda 表达式中的委托函数时保留参数 i?