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