javascript - 按下按钮时如何将子元素隐藏在 div 元素中?(不隐藏父母)
问题描述
我的 html 文件中有这个侧边栏,我想在其中包含各种内容。但是,我不能真正把它全部放在里面。我想隐藏父 div 内的默认子级side-bar
。起初我尝试制作一个循环遍历所有孩子并将他们的样式更改为style.display = 'none';
. 那没有用。我收到错误消息:
code.js:128 Uncaught TypeError: Cannot set property 'display' of undefined
我当前的目标代码是(在 javascript 中):
document.getElementById("other-stats").addEventListener("click",function()
{
for(var i = 0 ; i < document.getElementById("side-bar").children.length ; i++)
{
document.getElementById("side-bar").lastChild.style.display = 'none';
}
});
我很感激任何人都可以给出的任何答案,但我没有在我的代码中使用 Jquery,所以我希望有一些 javascript 答案。
我的html:
<div id="side-bar">
<div id="character-view-section">
<center>
<img style="width:150px ; height:200px ; margin-top:50px ;" alt="character">
</center>
</div>
<div id="stats-section">
<p id="health" style="border:solid 2px crimson ; background-color: crimson ;" class="stats">
health: 100
</p>
<p id="stamina" style="border:solid 2px rgb(38, 168, 21) ; background-color: rgb(38, 168, 21) ;" class="stats">
stamina: 50
</p>
<p id="weapon" style="border:solid 2px rgb(20, 197, 220); ; background-color: rgb(20, 197, 220) ;" class="stats">
weapon: NOT DETERMINED
</p>
</div>
<div id="inventory-section">
</div>
<center>
<button id="use-item">
use item
</button>
</center>
<button id="other-stats">
other stats
</button>
</div>
这是我制作的整个侧边栏 div。除了酒吧之外,这里的所有东西都是我想隐藏的,以便放置其他元素。
解决方案
您可以#side-bar > *
用作选择器来选择侧边栏的子元素,然后您可以循环通过它们以编程方式隐藏它们。
document.getElementById("other-stats").addEventListener("click",function()
{
var childElements = document.querySelectorAll("#side-bar > *" )
for(var i = 0 ; i < childElements.length ; i++)
{
childElements[i].style.display = 'none';
}
});
推荐阅读
- nswagstudio - 更改 NSwagStudio 序列化设置以允许 Nulls
- javascript - 如何在 React js 中使用 jQuery/javascript 文件进行设计
- rasa-nlu - 有没有小鸭的替代品?
- javascript - 字体在 iOS 的 Cordova 应用程序上随机加载
- docker - 如何监控容器内运行的进程
- asp.net - 为什么 Gridview 在单击按钮时会丢失 BackColor
- firebase - Firebase - 查看特定页面的所有内容
- zabbix - zabbix - 安装多个ezbbix代理版本
- docusignapi - DocuSign 返回 URL
- project-reactor - Reactor Netty 中的 ByteBuf 分配器