我正在尝试制作一个战舰游戏,表格由 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]);
});
但是控制台会抛出该关键字的类型错误
Uncaught TypeError: Cannot read property ‘index’ of null
最佳答案
看起来您正在使用jquery。 (js中没有index方法) 尝试使用目标事件
table.addEventListener("click",function(event){
let col= $(event.target).closest('td').index();
let row= $(event.target).closest('tr').index();
shot([row,col]);
});
关于javascript - 如何为每个没有唯一 id 的按钮表设置 EventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852656/