javascript - 如何使用该 div id 内的按钮将“getelementbyid”值设置为 div id
问题描述
我有大约 300 个 div 的内容,我需要能够隐藏当前的 div 并在单击按钮时根据其 id 显示一个新的 div。大多数设置为一个接一个地流动,其中一些根据您单击的按钮循环回以前或将来的 div 标签。每个以前的 div 都需要隐藏,每个新的 div 都需要在点击时显示。我可以布置每个单独的函数,但我宁愿设置一个脚本或函数来设置 getelementbyid div id 隐藏和 div id 显示,以便它可以设置 onclick 并且我最终不会使用 300 多个函数
HTML 代码
<div id="myDIV" >
<p>Sample Text Goes Here</p>
<div>
<button type="button" onclick="myFunction(); myFunction2();">
Next</button>
</div>
</div>
<div id="myDIV2" style="display:none">
<p>Next sample Text Goes Here</p>
<div>
<button type="button" onclick="myFunction(); myFunction2();">
Back</button>
<button type="button" onclick="myFunction2(); myFunction3();">
Next</button>
</div>
</div>....
Javascript代码
function myFunction(){var x = document.getElementById("myDIV");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
function myFunction2() {var x = document.getElementById("myDIV2");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
function myFunction3() {var x = document.getElementById("myDIV3");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
function myFunction4() {var x = document.getElementById("myDIV4");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
为了清楚起见,这个脚本在我的 div 标签下,在页面的正文部分。非常感谢任何提示或帮助
解决方案
只需将 div 的 id 作为参数传递
<div id="myDIV" >
<p>Sample Text Goes Here</p>
<div>
<button type="button" onclick="myFunction('myDIV', 'myDIV2');">
Next</button>
</div>
</div>
// 1 method for all divs
function myFunction(currentID, nextID) {
var currentDIV = document.getElementById(currentID);
var nextDIV = document.getElementById(nextID);
currentDIV.style.display = "none";
nextDIV.style.display = "block";
}
推荐阅读
- reactjs - 如何使用 reactJS 在 select.creatable 中更改位置创建新选项?
- amazon-aurora - AWS Aurora 和自动增量
- jquery - 在 fontawesome SVG 中替换和动画图标
- domain-driven-design - 可以删除域事件吗?
- android - 什么用(API 28)替换不推荐使用的 getFragmentManager() 方法?
- react-native - 无法从 react-native 取消链接 Testfairy
- javascript - 单词搜索游戏。如何搜索网格并突出显示结果?
- node.js - 谷歌云功能 - Firestore 查询快照大小返回未定义
- java - 客户端只能在同一台计算机上连接到服务器
- java - Ract-Native Android 构建失败 - 无法找到请求目标的有效认证路径