简体   繁体   中英

How can I reuse a JavaScript function for different buttons?

I want to use one javascript function which can hide or show different divs (none/block). But for every different button clicked, a different div should show or hide.

My function is as follows:

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

And the buttons are:

<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>

The divs I want to show/hide are like these and must be linked to one button:

<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>

So if I press the gender button, I only want the div with id="gender" to show up. I hope some one can help! Thanks in advance.

Just send an id of the target div to your function

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

then in your function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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