简体   繁体   English

将目标元素 ID 分配给 JavaScript 中的变量

[英]Assign Target Element id to variable in JavaScript

I want to write a code in JavaScript, which will get Id of an element(in my case clicking on table. each <td> has it own id), and than using this ID I want to access corresponding element in Array.我想在 JavaScript 中编写一个代码,它将获得一个元素的 Id(在我的情况下单击 table。每个<td>都有它自己的 id),而不是使用这个 ID,我想访问 Array 中的相应元素。 So many tries but with no success.尝试了很多次,但没有成功。 Below is my code, please help me understand what I am doing wrong.下面是我的代码,请帮助我理解我做错了什么。 what i can do to fix it?我能做些什么来解决它? :( :(

const items = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],[1, 4, 7],[2, 5, 8]];
let cells = document.querySelectorAll(".cell");
function findIndex() {
  let index;
  for (let i = 0; i < cells.length; i++) {
    cells[i].addEventListener("click", function (e) {
      index = Number(e.target.id);
    });
  }
  return index;
}

console.log(items[findIndex()]);

You wrote the listener for click.你为点击编写了监听器。 Function inside the eventListener will be called only after you click on the specific table cell.只有单击特定表格单元格后,才会调用 eventListener 内部的 Function。 Below I posted the example where after clicking I access and log into the console a corresponding value from the array.下面我发布了示例,单击后我访问并登录到控制台中的数组中的相应值。

So this is how you should access your value items[Number(event.target.id)] and pay attention that it'll be executed only after your click on the cell.所以这就是你应该如何访问你的值items[Number(event.target.id)]并注意它只会在你点击单元格后执行。

 const items = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8] ]; document.querySelectorAll('.cell').forEach((currentElement) => { currentElement.addEventListener("click", function(event) { console.log(items[Number(event.target.id)]); }) });
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Solution</title> </head> <body> <table> <tr> <td id="0" class="cell">Row 1</td> <td id="1" class="cell">Row 2</td> <td id="2" class="cell">Row 3</td> </tr> <tr> <td id="3" class="cell">Row 4</td> <td id="4" class="cell">Row 5</td> <td id="5" class="cell">Row 6</td> </tr> </table> </body> </html>

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

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