简体   繁体   English

如何将事件侦听器添加到表中的每个单元格?

[英]How to add event listener to each cell in a table?

Let's say I have a grid that looks like this (the numbers inside the cell is just for labeling, it could just be empty cells): 假设我有一个看起来像这样的网格(单元格中的数字仅用于标记,它可能只是空单元格):

在此处输入图片说明

Written in HTML as follows: 用HTML编写,如下所示:

<table>
      <tr>
        <td>0 </td>
        <td>1 </td>
      </tr>
      <tr>
        <td>2 </td>
        <td>3 </td>
      </tr>
</table>

There are two things that I would like to do: 我想做两件事:

  1. Add some JavaScript code that log the number of the cell to the console when each cell is clicked. 添加一些JavaScript代码,以在单击每个单元格时将单元格的编号记录到控制台。 Here is how I did it: 这是我的做法:
 const cells = document.querySelectorAll('td'); for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function () { console.log(i); }); } 

But the console always returns the value 4 wherever I click the table. 但是,无论我在哪里单击表,控制台始终返回值4。 My questions are: 我的问题是:

  1. By adding cells[i].addEventListener in each iteration of the for loop, does it add an event listener for each cell? 通过在for循环的每次迭代中添加cell [i] .addEventListener,是否为每个单元格添加一个事件侦听器?
  2. Why does the console always return 4 even if I clicked the cells[0], cells[\\1], cells[2] or cells[3]? 为什么即使单击cells [0],cells [\\ 1],cells [2]或cells [3],控制台也总是返回4?
  3. What should I do to make the console return the desired position in the array cells, ie return 0 if I clicked cells[0], return 1 if I clicked cells[\\1], return 2 if I clicked cells[2], return 3 if I clicked cells[3]? 我应该怎么做才能使控制台返回数组单元格中的所需位置,即如果单击cells [0],则返回0;如果单击cells [\\ 1],则返回1;如果单击cells [2],则返回2。 3如果我单击了单元格[3]?

Next, 下一个,

  1. The second thing that I would like to do is to change the colour of each cell depending on the colour that I chose from the colour picker as set by the HTML: <input type="color" id="colorPicker"> 我想做的第二件事是根据我从HTML设置的颜色选择器中选择的颜色来更改每个单元格的颜色: <input type="color" id="colorPicker">

Here is how I did it: 这是我的做法:

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

But the colour of the cell did not change. 但是细胞的颜色没有改变。

I don't plan to use jQuery, I would just like to use basic JavaScript that add an event listener to each cell. 我不打算使用jQuery,我只想使用向每个单元格添加事件侦听器的基本JavaScript。 I have tried to figure some ways out for hours but still clueless in the end. 我已经尝试了数小时的出路,但最终还是一无所知。 Could somebody please give some help? 有人可以帮忙吗? I really appreciate it, thanks! 非常感谢,谢谢!

is because you use "i" variable on your callback. 是因为您在回调中使用了“ i”变量。 And "i" have value : 4 at the end of your loop, so when you click callback, your app use this last value. 而且“ i”在循环的末尾具有值:4,因此,当您单击回调时,您的应用程序将使用最后一个值。

Just change your code by : 只需通过以下方式更改代码:

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

  });
}

And for you second case base on colorPicker : 第二种情况是基于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;
  });
}

live sample 现场样本

Since i is incrementing then after the for loop is complete i == cells.length. 由于i正在递增,因此在for循环完成之后,i == cells.length。

in place of... 代替...

 for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function () { console.log(i); }); } 

use... 采用...

 for (var i = 0; i < cells.length; i++) { cells[i].addEventListener('click', function (e) { console.log(e.target); }); } 

And the same for your latter example... 对于后面的示例也是如此...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM