首页 > 解决方案 > 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>

谢谢您的帮助...

标签: javascripthtml

解决方案


您可以将 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>


推荐阅读