javascript - 将 EventListener 应用于表格而不是每个单元格。如何?
问题描述
在下面的代码中它工作正常,但我将EventListener应用于 for 循环中表中的每个Cell而我只想将一个EventListener应用于表本身以更改background-color
for 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);
}
}
解决方案
您可以在表格上附加点击侦听器并使用 访问单元格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>
推荐阅读
- hyperledger-fabric - 超级账本优于以太坊
- keras - 扩展 Keras TensborBoard 回调以可视化模型预测
- mongodb - 如何在单个文档而不是数组中获得 $match 结果?
- node.js - 如何在 MongoDB 中同时进行“$and”和“$or”查询?
- varnish - 如何刷新firebase自定义域上的缓存?
- node.js - 带有 AWS 开发工具包 Node.js 的自定义 S3 服务器的自签名证书错误
- json - 我可以将部分数据提取到可快速解码的字符串中吗?
- node.js - wkhtmtopdf javascript不工作
- asp.net - 如何修复 ReferenceError:_gaq 未定义
- gltf - glTF accessor.max/min 验证