javascript - 如何为每个没有唯一 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 的属性“索引”
解决方案
看起来你正在使用 jquery。(js中没有索引方法)尝试使用目标事件
table.addEventListener("click",function(event){
let col= $(event.target).closest('td').index();
let row= $(event.target).closest('tr').index();
shot([row,col]);
});
推荐阅读
- html - HTML:列可以跨越标题行和正文行吗?
- c++ - 调用带有指针对象错误的指针变量
- python-3.x - 加入列表后从列表中格式化字符串
- mysql - 将 sql 转储恢复到正在运行的 mysql/mariadb docker 容器中
- asp.net-web-api - 无法将 IActionResult 转换为 bool
- jenkins - 如何将 ECS 与 Jenkins 集成
- python - 如何在整个 python 数据帧中寻找相似之处?
- capistrano - Capistrano:如果其中任何主机未通过检查,我如何触发所有主机上的任务?
- apache-spark - Spark 作业状态正在运行,但第一步启动的时间几乎是 20 分钟后
- r - 使用 purrr 重命名 tibbles 列表中的不同列