首页 > 解决方案 > 让地址链接在 JavaScript 中打开隐藏部分

问题描述

我是 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", "");
  }
}

标签: javascripthtmldisplay

解决方案


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

稍后您可以创建一个名为的类,该类将在将类赋予元素时将.show元素的显示更改为阻塞。

提醒:永远不要使用var, 使用let & const最新的语法。( ecma 脚本 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>


推荐阅读