首页 > 解决方案 > 单击以使用 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吗?

标签: javascript

解决方案


单击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>


推荐阅读