首页 > 解决方案 > 按下按钮时如何将子元素隐藏在 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。除了酒吧之外,这里的所有东西都是我想隐藏的,以便放置其他元素。

标签: javascripthtml

解决方案


您可以#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';
        }
});

推荐阅读