将事件侦听器应用于表而不是每个单元格.如何?



在下面的代码中,它工作正常,但我将事件侦听器应用于 for 循环中表中的每个单元格,而是我想只将一个事件侦听器应用于表本身以更改所选单元格background-color。我怎么能做到这一点?

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);
}
}

您可以将单击侦听器附加到表上并使用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>

当您单击表格时,首先检查它是否是 td,然后将背景颜色更改为您想要的任何颜色。

const table = document.getElementById("table");
table.addEventListener("click", (e)=>{
const element = e.target;
if(element.tagName === "TD"){
element.style.backgroundColor = "red"
}
});
<table id="table">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>

使用事件委派。在表上设置事件侦听器,然后询问事件目标(作为事件源的元素(是否为单元格td元素。如果是,则再次使用事件目标根据需要修改单元格(在这种情况下event.target将是相应的单元格元素(。

你可以在这里看到它。

const table = document.querySelector('table');
table.addEventListener('click', event => {
if (event.target.nodeName === 'TD') {
event.target.style.background = 'red';
}
});
<table>
<tr>
<td>cell1</td>
<td>cell2</td>
<tr>
</table>

单击单元格时,其背景颜色将更改为红色,即使只有侦听器分配给其父表也是如此。

在您的情况下,您应该删除行

tCell.addEventListener("click", fillSquare);

更改fillSquare函数,使其采用参数(元素目标(

function fillSquare (element) {
element.setAttribute("style", `background-color: ${color.value}`);
}

并像这样将事件侦听器添加到表中

const table = document.querySelector('select-parent-table');
table.addEventListener('click', event => {
if (event.target.nodeName === 'TD') {
fillSquare(event.target);
}
});

最新更新