[英]Click on HTML table and get row number (with Javascript, not jQuery)
我想知道如何單擊 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>
嘗試這個:
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>
@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.