首页 > 解决方案 > 不使用 ID 折叠文本

问题描述

我制作了以下脚本来折叠文本。

我的网站上有很多这样的可折叠框。我可以在没有身份证的情况下以某种方式制作这个吗?所以你只是得到一个在任何地方都相同的href标签,但它会折叠它旁边的DIV?

  function kadabra(zap) {
   if (document.getElementById) {
   var abra = document.getElementById(zap).style;
    if (abra.display == "block") {
    abra.display = "none";
    } else {
    abra.display= "block";
   }
   return false;
   } else {
   return true;
  }
  }
.meerinfobox {
  display: none;
  padding-left: 16px;
}
<a href="#" onclick="return kadabra('show1');">CLICK4MORE</a> Text Text
<div id="show1" class="meerinfobox">
<pre>
Text text text text text text text
</pre>
</div>

<p>

<a href="#" onclick="return kadabra('show2');">CLICK4MORE</a> Text Text
<div id="show2" class="meerinfobox">
<pre>
Text text text text text text text
</pre>
</div>

<p>

<a href="#" onclick="return kadabra('show3');">CLICK4MORE</a> Text Text
<div id="show3" class="meerinfobox">
<pre>
Text text text text text text text
</pre>
</div>

标签: javascripthtml

解决方案


您可以为您的案例使用委托。

const container = document.querySelector("#container");

container.addEventListener("click", kadabra);

function kadabra(event) {
  const section = event.target.closest("section");
  if (section !== null) {
    section.querySelector("div").classList.toggle("meerinfobox");
  }
}
.meerinfobox {
  display: none;
  padding-left: 16px;
}
<div id="container">
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="meerinfobox">
      <pre> Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="meerinfobox">
      <pre>Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="meerinfobox">
      <pre>Text text text text text text text </pre>
    </div>
  </section>
</div>


推荐阅读