我找不到我问题的适当答案。我在表中有行,每一行都包含一个按钮。如何找到我刚刚单击的按钮的行索引。
<tr>
<td>111</td>
<td>aaa</td>
<td><input type="submit" name="first" id="first" value="First" onclick="countRow(this.id)" /></td>
</tr>
<tr>
<td>222</td>
<td>bbb</td>
<td><input type="submit" name="sec" id="second" value="Second" onclick="countRow(this.id)" /></td>
</tr>
<tr>
<td>333</td>
<td>ccc</td>
<td><input type="submit" name="third" id="third" value="Third" onclick="countRow(this.id)" /></td>
</tr>
最佳答案
使用tbody标签和此javascript
function countRow(id) {
var table = document.getElementById('dataTable')
var tbody = table.getElementsByTagName('tbody')[0]
var rows = tbody.getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
<table id="dataTable">
<tbody>
<tr>
<td>111</td>
<td>aaa</td>
<td>
<input type="submit" name="first" id="first" value="First" onclick="countRow(this.id)" />
</td>
</tr>
<tr>
<td>222</td>
<td>bbb</td>
<td>
<input type="submit" name="sec" id="second" value="Second" onclick="countRow(this.id)" />
</td>
</tr>
<tr>
<td>333</td>
<td>ccc</td>
<td>
<input type="submit" name="third" id="third" value="Third" onclick="countRow(this.id)" />
</td>
</tr>
</tbody>
</table>