javascript - Javascript - 隐藏/显示 - 多个按钮 - 调用 1 个函数
问题描述
请问有人能解释一下这种情况吗?
我想对更多按钮使用相同的功能(隐藏/显示)。如何使用不同的按钮调用相同的功能?
我找到了如何使用一个按钮,但找不到 2 个或更多按钮的任何解决方案。
如果我点击 bt1,我想隐藏 div1,如果我点击 bt2,我想隐藏 div2。感谢您的任何帮助...
我目前的代码是:
function myFunction() {
var x = document.getElementById("div1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction()">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction()">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
谢谢您的帮助...
解决方案
您可以将 div 的 ID 作为参数传递给您的函数:
function myFunction(el) {
var x = document.getElementById(el);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button id="bt1" onclick="myFunction('div1')">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction('div2')">Button 2</button>
<div id="div2">div2</div>
推荐阅读
- java - 如何移动和组织 Eclipse 项目和工作区?
- angular - 问题是 ngfor 仅支持绑定到 Iterables,例如 Arrays
- c# - 使用内部构造函数实例化类
- javascript - 尝试启动 webpack 开发服务器(Ubuntu)
- python - 有人为 Windows 10 安装了 mlpack 库吗?
- express - 如何使用 Nuxt.js 生成一个静态应用程序,该应用程序在部署后使用 express 有一个发布请求?
- r - 分组连续周数
- elasticsearch - 使用字段而不是“_id”进行更多类似的查询
- jscript - 如何仅将密码传递给 HTTP 请求?
- javascript - 从传递给触发事件的无状态 React 组件中提取 HTML