【问题标题】:Is there a shorter more concise way to hide & show div with Javascript?有没有更简洁的方法来隐藏和显示 div 与 Javascript?
【发布时间】:2022-06-14 21:07:29
【问题描述】:

我正在创建一个仪表板,其中包含大约 20 个以“display: none;”开头的 div。

当使用侧边栏中的 .onClick() 时,它会显示一个特定的 div 并保持隐藏所有其他 div。 我使用了为每个div创建一个函数的经典解决方案,但是非常冗长,代码看起来很乱。

有没有更好更简洁的方式来使用 Javascript 实现这一点?

这是我的代码:

function presale() {
  var x = document.getElementById("presale");
  var y = document.getElementById("claim");
  var z = document.getElementById("stake");
  if (x.style.display === "grid") {
    x.style.display = "none";
  } else {
    x.style.display = "grid";
    y.style.display = "none";
    z.style.display = "none";
  }
}

function claim() {
  var x = document.getElementById("presale");
  var y = document.getElementById("claim");
  var z = document.getElementById("stake");
  if (y.style.display === "grid") {
    y.style.display = "none";
  } else {
    x.style.display = "none";
    y.style.display = "grid";
    z.style.display = "none";
  }
}

function stake() {
  var x = document.getElementById("presale");
  var y = document.getElementById("claim");
  var z = document.getElementById("stake");
  if (z.style.display === "grid") {
    z.style.display = "none";
  } else {
    x.style.display = "none";
    y.style.display = "none";
    z.style.display = "grid";
  }
}
*,
html {
  color: #fff;
  background-color: black;
}

#presale,
#claim,
#stake
/* Here I have many other divs like below */

{
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  <link rel="stylesheet" href="MOD.CSS">
  <script src="main2.js"></script>
  <title>Base Template</title>
</head>

<body>
  <div>
    <ul>
      <!-- Here I have other 20 options like the above -->
      <li onclick="presale()">Presale</li>
      <li onclick="claim()">Claim</li>
      <li onclick="stake()">Stake</li>
      <!-- Here I have other 20 options like the above -->
    </ul>
    <div id="presale">
      <h1>Presale</h1>
    </div>
    <div id="claim">
      <h1>Claim</h1>
    </div>
    <div id="stake">
      <h1>Stake</h1>
    </div>
  </div>
</body>

</html>

有没有更好的方法来做到这一点,而无需创建一个函数并为每个 div 一遍又一遍地重复相同的事情?

【问题讨论】:

  • 如果您使用的是 React 或 Vue 等前端框架,则可以使用数据绑定来实现。

标签: javascript html jquery css


猜你喜欢
  • 1970-01-01
  • 2013-11-14
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多