首页 > 解决方案 > 无法多次按下重置按钮

问题描述

这是一个 etch-a-sketch 项目,我从 2 天以来一直在尝试编写代码,我终于结束了。我只需要弄清楚最后一件事。重置按钮只能工作一次,之后我必须刷新页面才能重置网格并生成新的自定义网格。

HTML

在这里,我有一个用于重置网格的按钮。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>

        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="reset.css">
        <title>

        </title>

    </head>
    <body>

        <div id="rs" >
            <button id="reset"> Reset Grid!</button>
        </div>      

        <div id="container">  </div>


               <script src="script.js">        </script>
    </body>
</html>

CSS

这是CSS文件。我正在设置一个容器和之前在HTML文件中显示的重置按钮来重置网格并显示

.active {
    background-image: linear-gradient(90deg , green , yellow);
    border: none;
}

#container {
    border: gray solid 1px;
    height: 500px;
    width: 500px;
    margin-left: auto;
    margin-right: auto;
    position: relative;
    margin-top: 30px;
    display: grid;
   grid-template-columns: repeat(16,1fr);
   grid-template-rows: repeat(16,1fr);


}


#reset {
    display: block;
    text-align: center;
}

JS

使用 JS 将多个 div 追加到父容器中填充网格。

默认启动

const cont = document.getElementById('container');


for (let a=0; a < 256; a++){ 
    let him = document.createElement('div');
    him.classList.add('divi');
    him.setAttribute('style','border : solid 1px gray;')
    cont.appendChild(him);    
    him.addEventListener('mouseover', (e) => {
        him.classList.add('active');
        him.setAttribute('style','border :none;')
    })    
}

重置。基本上清除网格并生成一个具有用户定义网格大小的新网格。但只能工作一次,所以我必须在点击一次后刷新页面

let btn = document.getElementById('reset');


btn.onclick = reseter;

   function reseter () {
    document.getElementById('container').remove();
    let size = prompt('SIZE');
    let new_cont = document.createElement('div');
    new_cont.style.border = 'solid 1px gray';
    new_cont.style.height = '500px';
    new_cont.style.width = '500px';
    new_cont.style.marginLeft = 'auto';
    new_cont.style.marginRight = 'auto';
    new_cont.style.marginTop = '30px';
    new_cont.style.display = 'grid';
    new_cont.style.gridTemplateColumns = `repeat(${size},1fr)`;
    new_cont.style.gridTemplateRows = `repeat(${size},1fr)`;



    for (let ip = 0; ip < size*size; ip++) {
        let newDiv = document.createElement('div');
        newDiv.classList.add('divi');
        new_cont.appendChild(newDiv);
        newDiv.style.border = '1px solid gray';
        newDiv.addEventListener('mouseover', (e) => {
            newDiv.classList.add('active');
            newDiv.style.border = 'none';

        })


    }



    document.body.appendChild(new_cont);

   }

我怎样才能解决这个问题?

标签: javascript

解决方案


代替

document.getElementById('container').remove();

采用

document.getElementById('container').innerHTML = '';

您正在做的是删除您已将事件绑定到的整个元素。第一次单击重置按钮时,元素被删除,因此第二次找不到容器元素,并且什么也没有删除。

您想要做的是清空用于附加其他 div 的容器,其中.innerHTML = '';


推荐阅读