无法弄清楚为什么我的脚本停止工作。 。

时间:2019-01-17 11:09:11

标签: javascript

我正在编写一个简单的蚀刻草图程序。我有2个按钮。 1重置屏幕,另一个重置新屏幕,让您选择绘制区域中的像素数。默认大小有效,而重置有效。当我单击新按钮并设置绘制区域中的像素数更新时,事件监听器停止工作,并且鼠标悬停将不再更改div的背景颜色。这是我的代码:

const screen = document.querySelector('.screen')
const clearButton = document.querySelector('.clear-btn');
const newButton = document.querySelector('.new-btn');
var size = 64;

function createGrid(size) {
  document.styleSheets[0].cssRules[3].style["grid-template-columns"] = "repeat(" + size + ", 1fr)"
  document.styleSheets[0].cssRules[3].style["grid-template-rows"] = "repeat(" + size + ", 1fr)"
  console.log('createGrid');
  for (i = 0; i < size*size; i++) { 
    const grid = document.createElement('div');
    grid.classList.add('grid');
    grid.style.cssText = 'color: #cccccc; background: #cccccc; border: solid 1px lightgrey;';      
    screen.appendChild(grid);
  }
}

function reset() {
  for (i = 0; i < size*size; i++) { 
  grid[i].style.backgroundColor = "#cccccc";
  }
}

function newSize(){
  let userResponse = prompt("Please enter size of canvas: ", "");
  size = parseInt(userResponse);
  remove();
  createGrid(size);
}


function remove(){
  while (screen.firstChild) {
    console.log(size);
    screen.removeChild(screen.firstChild);
  }
}

createGrid(size);

clearButton.addEventListener('click', reset);
newButton.addEventListener('click', newSize);

var grid = document.getElementsByClassName('grid');
Array.from(grid).forEach((tile) => {
  tile.addEventListener('mouseover', (e) => {
    e.target.style.background = '#0d0d0d';

  });
})

2 个答案:

答案 0 :(得分:1)

创建网格时,需要添加事件侦听器。删除网格,该网格已附加了事件原始事件侦听器,而新创建的网格未附加任何内容:

input {
   padding-bottom: 100px;
   width: 500px;
}

您还可以查看event delegation,这样就不必为每个单元格添加一个侦听器,也可以将其添加到容器中。

答案 1 :(得分:1)

这样做的原因是您现在有了新的div。您的侦听器已附加到原始HTMLNode,现在添加了新的HTMLNode,它们没有附加任何侦听器。解决方案是: -清理旧的监听器(在删除功能中) -附加新的侦听器(在newSize函数中)

将最后一个部分(从{ "presets": [ "env" ], plugins: [ "babel-plugin-transform-runtime" ] } 移动到一个函数,然后在新的size函数的末尾调用它,如下所示:

Option Explicit
Sub ReDimTest()
    Dim counter As Long
    counter = 0
    Dim arr() As String

    'read first element from file
    Dim firstItem As String: firstItem = "1"
    'increment counter
    counter = counter + 1
    ReDim Preserve arr(counter)
    arr(counter) = firstItem
    'read second element from file
    Dim secondItem As String: secondItem = "2"
    'increment counter
    counter = counter + 1
    ReDim Preserve arr(counter)
    arr(counter) = secondItem
End Sub

现在,您的newSize函数是这样的:

var grid = document.getElementsByClassName...

然后删除项获得附加项:

function atachListeners() {
  const grid = document.getElementsByClassName('grid');
  Array.from(grid).forEach(tile => {
    tile.addEventListener('mouseover', ...);
  });
};

实施removeListeners()方法,我留给您做作业:)