繁体   English   中英

如何为不同的按钮重用 JavaScript 函数?

[英]How can I reuse a JavaScript function for different buttons?

我想使用一个可以隐藏或显示不同 div(无/块)的 javascript 函数。 但是对于每个不同的按钮点击,不同的 div 应该显示或隐藏。

我的功能如下:

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

按钮是:

<div><button id="subclass_button" onclick="visibility()">Age</button>
      <div><button id="subclass_button" onclick="visibility()">Death Place</button>
      <div><button id="subclass_button" onclick="visibility()">Death Cause</button>
      <div><button id="subclass_button" onclick="visibility()">Music Genre</button>
      <div><button id="subclass_button" onclick="visibility()">Gender</button>
      <div><button id="subclass_button" onclick="visibility()">Birthplace</button>

我想显示/隐藏的 div 是这样的,必须链接到一个按钮:

<div id="gender">
        <button>Male</button>
        <button>Female</button>
      </div>

      <div id="deathPlace">
        <input type="text" class="form-control" placeholder="Search for a death place..." >
        <button ng-click="doMyAction()" type="button">Search</button>
      </div>

      <div id="birthplace">
        <input type="text" class="form-control" placeholder="Search for a birthplace..." >
        <button ng-click="doMyAction()" type="button">Search</button>
      </div>

因此,如果我按下性别按钮,我只希望显示 id="gender" 的 div。 我希望有人能帮帮忙! 提前致谢。

只需将目标 div 的 id 发送到您的函数

<div><button id="subclass_button" onclick="visibility('gender')">Gender</button>

然后在你的函数中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM