javascript - 单击以使用 Javascript 显示 div
问题描述
我的网站上有一个页面,我在其中显示一个内容块并为用户提供单击“查看更多”以显示更多内容的选项。
这是我当前的演示。
HTML:
<p>
<a href="#" id="category36SeeMore">See more</a>
</p>
<div class="category36">
test
</div>
<div class="category36" style="display:none;">
test
</div>
<div class="category36" style="display:none;">
test
</div>
<div class="category36" style="display:none;">
test
</div>
有人可以给我一些关于如何为#category36SeeMore创建函数的指示,以便它显示该类的所有 divcategory36
吗?
解决方案
单击category36SeeMore
时,您可以先获取其 id,然后SeeMore
从中替换,如下所示:
const id = this.id.replace('SeeMore', '')
因此,您可以从中获取实际的类名category36
。然后,您可以使用以下命令找到该类的所有元素:
document.querySelectorAll('.' + id)
最后使用.forEach
,更改所有元素的显示样式block
以使所有元素再次可见。
演示:
const btn = document.getElementById("category36SeeMore");
btn.addEventListener("click", function(e){
e.preventDefault();
const id = this.id.replace('SeeMore', '')
document.querySelectorAll('.' + id).forEach(el=>el.style.display = 'block')
});
.category36 {
margin: 5px;
padding: .5rem;
box-shadow: 2px 2px 5px rgba(0,0,0,0.03);
border-radius: 4px;
background: Skyblue;
border-bottom: 1px solid #F9F2D6;
border-right: 1px solid #F9F2D6;
}
<p>
<a href="#" id="category36SeeMore">See more</a>
</p>
<div class="category36">
test
</div>
<div class="category36" style="display:none;">
test
</div>
<div class="category36" style="display:none;">
test
</div>
<div class="category36" style="display:none;">
test
</div>
推荐阅读
- raspberry-pi - 传感器多线程树莓派
- websocket - JMeter WebSocket 插件 - 关闭 SignalR 连接
- angular - p 日历上的 onClose 不会触发
- java - 在泛型方法中处理类型创建
- android - Android 更新到 gradle 3.2.1 [INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION] 在 Android <=6
- c# - HtmlAgilityPack HtmlDocument 访问头元素
- php - Ghostscript / pdfwrite 以彩色 PDF 和 CMYK 颜色而不是 RGB 生成灰色页面
- ios - MPVolumeView 在 iPad 上不显示扬声器选项
- network-programming - 是否有任何标准 URL 用于检测是否存在强制门户?
- smali - dexlib2 - Methodanalyzer resulting in UnresolvedClassException for certain classes