![](/img/trans.png)
[英]How to add event listener to each row of a table, and to pass a parameter with the function
[英]How to add event listener to each cell in a table?
假設我有一個看起來像這樣的網格(單元格中的數字僅用於標記,它可能只是空單元格):
用HTML編寫,如下所示:
<table>
<tr>
<td>0 </td>
<td>1 </td>
</tr>
<tr>
<td>2 </td>
<td>3 </td>
</tr>
</table>
我想做兩件事:
const cells = document.querySelectorAll('td'); for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function () { console.log(i); }); }
但是,無論我在哪里單擊表,控制台始終返回值4。 我的問題是:
下一個,
<input type="color" id="colorPicker">
這是我的做法:
const cells = document.querySelectorAll('td');
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', function () {
const color = document.querySelector('#colorPicker').value;
cells[i].style.backgroundColor = color;
});
}
但是細胞的顏色沒有改變。
我不打算使用jQuery,我只想使用向每個單元格添加事件偵聽器的基本JavaScript。 我已經嘗試了數小時的出路,但最終還是一無所知。 有人可以幫忙嗎? 非常感謝,謝謝!
是因為您在回調中使用了“ i”變量。 而且“ i”在循環的末尾具有值:4,因此,當您單擊回調時,您的應用程序將使用最后一個值。
只需通過以下方式更改代碼:
const cells = document.querySelectorAll('td');
for (var i = 0; i < cells.length; i++) {
console.log(cells[i].innerText);
cells[i].addEventListener('click', (event) => {
console.log(event.target.innerText); // Take the text node from the element who fire the click event.
// If you don't want to use innerText, you can do like this.
console.log(
//We transform querySelectorAll to traversable array. Then we find index of current event target.
Array.from(document.querySelectorAll('td')).findIndex(e => e === event.target)
);
});
}
第二種情況是基於colorPicker的:
const cells = document.querySelectorAll('td');
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', function (event) {
const color = document.querySelector('#colorPicker').value;
event.target.style.backgroundColor = color;
});
}
由於i正在遞增,因此在for循環完成之后,i == cells.length。
代替...
for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function () { console.log(i); }); }
采用...
for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function (e) { console.log(e.target); }); }
對於后面的示例也是如此...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.