我正在尝试将 onclicks 分配给第一行中的 td,以便单击第一个 TD 输出“1”,单击第二个 TD 输出“2”等。
问题是当我实际单击调用 onclick 时,我总是得到“3”,因为那是 onclick 使用的变量的最后一个值。
有没有办法让每次点击都返回我想要的唯一号码?
window.onload = function() { //Wait for the DOM to load.
table = document.getElementById('myTable');
for (i = 0; cell = table.rows[0].cells[i]; i++) {
console.log(i); // logs 0, 1, 2
cell.onclick=function(){ console.log(i);} // Want to get 0,1, or 2, but always get 3.
}
}
<table id=myTable>
<tr>
<td>COL1</td>
<td>COL2</td>
<td>COL3</td>
</tr>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
<tr>
<td>four</td>
<td>five</td>
<td>six</td>
</tr>
</table>