javascript - 不使用 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>
解决方案
您可以为您的案例使用委托。
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>
推荐阅读
- scheme - 在 Scheme 中使用 sect 和 slot
- assembly - 如何初始化 16 位半浮点数(ARM32 的 GAS)?
- angular - 如何配置 spring-boot-security 以使用登录页面对所有页面中的用户进行身份验证
- java - Java 应用程序生成一个应用程序并结束。应用程序有时也会被杀死
- sonarqube - 使用 sonarqube 对 cshtml 文件进行自定义代码分析
- reactjs - React-Query 知道数据何时发生变化?
- python - 在 Google Colab 笔记本中从 Cython 代码调用 Python 函数
- c# - 连接到 H2 数据库
- python - Python 枚举属性可以有一个空字符串吗?
- python - 按最小属性值对类实例的元组列表进行排序