[英]Click on HTML table and get row number (with Javascript, not jQuery)
I would like to know how to click on a button in an HTML table and get the row and column number returned to me: For example, with the following table:我想知道如何单击 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>
Try this:尝试这个:
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>
Most generic version of @Gremash js function @Gremash js 函数的最通用版本
function getId(element) {
alert("row" + element.closest('tr').rowIndex +
" -column" + element.closest('td').cellIndex);
}
试试这个代码: alert(document.getElementById("yourTableId").childNodes[1].childElementCount);
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.