【问题标题】:Let address link open hide section in JavaScript让地址链接在 JavaScript 中打开隐藏部分
【发布时间】:2021-10-12 03:23:30
【问题描述】:

我是 JS 的新手,所以我的问题是,如果我有很多部分并且我可以在单击按钮时打开它们(默认情况下它们是 display: none;,并在单击同一页面上的菜单按钮时打开)。我需要创建链接,如果有人在地址框中输入,则该部分会打开......但是如果它的display: none; 按地址创建,该怎么做?也许我错了,您可以提出一些更好的方法吗?

<section style="display: none;" id="sectionIepirkumi" class="w3-container w3-threequarter section">
  <div id="sectionTopLine" class="w3-border-top w3-border-green"></div>
  <h5 id="sectionAddress" class="w3-margin-bottom">
    <a id="sectionAddressFirstPageLink" class="sectionAddressLink" onclick="openSection('sectionFirstPage')">
          Sākumlapa </a>/
    <a class="sectionAddressLink" onclick="openSection('sectionAboutSchoolPage')"> Par Skolu </a>/
    <a class="" style="font-weight: bold;"> IEPIRKUMI</a>
  </h5>
  <div id="sectionBottomLine" class="w3-border-top w3-border-green w3-margin-bottom"></div>
  <div class="w3-panel w3-border">
    <h3>Uz doto momentu nav aktuālu iepirkumu!</h3>
  </div>
</section>
function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}

【问题讨论】:

  • 你在哪里调用 myFunction?

标签: javascript html display


【解决方案1】:

你让它变得复杂了,因为它(而不是使用 if..else)有一个classList 的方法,它可以让你切换你想要的元素的类。方法是toggle()

稍后您可以创建一个名为 .show 的类,当该类被赋予该元素时,它会将您的元素的显示更改为 block

提醒:永远不要使用var,使用最新语法let &amp; const。 (ecma-script 6)

function myFunction() {
  const container = document.getElementById('sectionIepirkumi');
  
  container.classList.toggle('show');
};

document.querySelector('button').addEventListener('click', myFunction);
.show {
  display: block !important;
}
<button type='button'>Click</button>

<section style="display: none;" id="sectionIepirkumi" class="w3-container w3-threequarter section">
  <div id="sectionTopLine" class="w3-border-top w3-border-green"></div>
  <h5 id="sectionAddress" class="w3-margin-bottom">
    <a id="sectionAddressFirstPageLink" class="sectionAddressLink" onclick="openSection('sectionFirstPage')">
          Sākumlapa </a>/
    <a class="sectionAddressLink" onclick="openSection('sectionAboutSchoolPage')"> Par Skolu </a>/
    <a class="" style="font-weight: bold;"> IEPIRKUMI</a>
  </h5>
  <div id="sectionBottomLine" class="w3-border-top w3-border-green w3-margin-bottom"></div>
  <div class="w3-panel w3-border">
    <h3>Uz doto momentu nav aktuālu iepirkumu!</h3>
  </div>
</section>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2023-04-01
    • 1970-01-01
    • 2011-06-07
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多