首页 > 解决方案 > 具有特定类的元素数组在 setTimeout 中变得未定义

问题描述

我正在使用 JavaScript 文件来隐藏具有相同类名的各种 div,程序尽可能地隐藏它们,但是当我希望它们在“x”秒后可见时,元素数组变得未定义并且长度为 0 ,不知道发生了什么。我尝试将“lowerDash”更改为全局变量但无济于事。

function newBaseHandler(){

    if (document.getElementById("Base6").innerHTML == `<br><p>Create new base</p>`) {
        let lowerDash = document.getElementsByClassName("LowerDashboard");
        let message = document.getElementById("Message");
        for (let button of lowerDash) {
            button.style.visibility = "hidden";
        }

        message.innerHTML = `<br><p>Base created successfully</p>`;

        setTimeout(function() {
            message.innerHTML = ``;
            console.log(lowerDash.length);
            for (let button of lowerDash) {
                button.style.visibility = "visible";
            }
        }, 1000);

    }

}

标签: javascripthtmlcss

解决方案


如果您希望它们在超时后再次可见,请尝试

button.style.visibility = "visible"

在你的 for 循环 insie setTimeout


推荐阅读