每次页面加载都会触发“点击”事件监听器

时间:2020-01-25 22:42:01

标签: javascript

我目前正在研究Odin项目,并且正在处理一个JavaScript项目,该项目让我创建一个16x16网格和一个按钮,该按钮可以清除当前网格并创建一个新的网格,其大小由用户。目前,我的按钮事件监听器似乎在每次加载页面时启动,而不是仅在单击按钮时启动。这是我的js代码:

const container = document.getElementById("container");

function createGrid(lateralSize){
    for (var i = 0; i < lateralSize**2; i++){
        let content = document.createElement('div');
        content.classList.add('content');
        container.appendChild(content);
    }
    if (lateralSize){
        container.style.gridTemplateColumns = "repeat(" + lateralSize + ",1fr)";
    }
    const box = document.querySelectorAll('div.content');
    box.forEach((box) => {
        box.addEventListener('mouseover', changeColor);
    });
    let changeLight = 0;
    let decreasingLigth = 0;
    function changeColor(e) {
      e.target.style.background = "rgb(" + defaultRandomColor(changeLight,changeLight,changeLight) + ")";
      if ((changeLight < 255 && decreasingLigth == 0) || changeLight == 0){
        changeLight ++;
        decreasingLigth = 0;
      } else {
        changeLight --;
        decreasingLigth = 1;
      }
      console.log(changeLight);
    }   
}

createGrid(16);

function clearAndResize() {
    while (container.firstChild) {
      container.removeChild(container.firstChild);
    }
    let gridLateralSize = prompt("How many squares do you want? from 1 to 100 ");
    while (gridLateralSize < 1 || gridLateralSize > 100) {
      gridLateralSize = prompt("How many squares do you want? from 1 to 100 ");
    }
      createGrid(gridLateralSize);
  }

  function defaultRandomColor(randomR = Math.floor(Math.random() * 255),
                              randomG = Math.floor(Math.random() * 255),
                              randomB = Math.floor(Math.random() * 255)) {
    return randomR + "," + randomG + "," + randomB;
  }

  const btn = document.getElementById('button');
  btn.addEventListener("click", clearAndResize())

0 个答案:

没有答案