首页 > 解决方案 > 将 EventListener 应用于表格而不是每个单元格。如何?

问题描述

在下面的代码中它工作正常,但我将EventListener应用于 for 循环中表中的每个Cell而我只想将一个EventListener应用于表本身以更改background-colorfor selected Cell。我怎么能这样做?

let height, width, color, reset;
const error = document.querySelector('#error');
function makeGrid(event) {
    event.preventDefault();
    clrGrid();
    height = document.querySelector("#inputHeight").value;
    width = document.querySelector("#inputWidth").value;
    if (height > 50 || width > 50 || height < 1 || width < 1) {
        if (!error.classList.contains("error")) {
            error.classList.toggle("error");
            error.innerText = "the dimension has to be smaller than 50 and bigger than 0";
        }
    } else {
        error.innerText = "";
        error.classList.remove("error");
        for (let x = 0; x < height; x++) {
            const tRow = document.querySelector("#pixelCanvas").insertRow(x);

            for (let y = 0; y < width; y++) {
                const tCell = tRow.insertCell(y);
                tCell.addEventListener("click", fillSquare);
            }
        }
    }
}

// Apply Color to Cells
color = document.querySelector('#colorPicker');
function fillSquare () {
    this.setAttribute("style", `background-color: ${color.value}`);
}

// Clear Canvas Grid
canvas = document.querySelector("#pixelCanvas");
function clrGrid() {
    error.innerText = "";
    error.classList.remove("error");
    while (canvas.firstChild){
        canvas.removeChild(canvas.firstChild);
   }
}

标签: javascript

解决方案


您可以在表格上附加点击侦听器并使用 访问单元格event.target

您可以在下面找到有关如何使用它的小演示。

document.getElementById('table').addEventListener('click', function(event) {
  const target = event.target;
  
  if (target.tagName.toLowerCase() === 'td') {
    target.style.background = 'blue';
  }
});
<table id="table">
  <tr>
    <td>Content</td>
    <td>Content</td>
  </tr>
  <tr>
    <td>Content</td>
    <td>Content</td>
  </tr>
</table>


推荐阅读