我想知道如何单击 HTML 表格中的按钮并获取返回给我的行号和列号:例如,下表:
<table>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
<tr>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
<td><input type="button" value="button"></td>
</tr>
</table>
我如何使用 JavaScript 单击第二行中的第一个按钮并让它告诉我我单击了第二行中的第一个单元格?每个按钮是否需要具有唯一 ID?
最佳答案
试试这个:
function getId(element) {
alert("row" + element.parentNode.parentNode.rowIndex +
" - column" + element.parentNode.cellIndex);
}
<table>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
<tr>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
<td><input type="button" value="button" onclick="getId(this)"></td>
</tr>
</table>
关于javascript - 单击 HTML 表并获取行号(使用 Javascript,而不是 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29042140/