首页 > 解决方案 > 如何为每个没有唯一 ID 的按钮表设置 EventListener?

问题描述

我正在尝试制作战舰游戏,该表由 10 行和 10 列按钮组成,每个按钮没有唯一的 id

<table id="myTable">
      <tr >
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
      </tr>
      <tr >
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
        <td><button type="button"></button></td>
      </tr>
    <!-- it's quite longer-->
</table>

单击任何按钮时获取单元格的坐标,我这样做了,但我返回

table.addEventListener("click",function(){
    let col=this.closest('td').index();
    let row=col.closest('tr').index();
    shot([row,col]);
});

但是控制台会为此关键字抛出 typeError

未捕获的类型错误:无法读取 null 的属性“索引”

标签: javascripthtmldom

解决方案


看起来你正在使用 jquery。(js中没有索引方法)尝试使用目标事件

table.addEventListener("click",function(event){
    let col= $(event.target).closest('td').index();
    let row= $(event.target).closest('tr').index();
    shot([row,col]);
});
还需要检查目标事件是您需要的 td 还是 tr


推荐阅读