我有以下 fiddle - 我正在测试获取表中数据的概念。目前,当我单击单元格时,我可以获取特定单元格中显示的值。
此外,我希望能够获取单击单元格的行索引和列索引。这里有人知道如何做到这一点吗?
var tbl = document.getElementById("recordingTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
<table cellspacing="1" id="recordingTable">
<!-- this is the head element -->
<thead class="callView">
<!--specify the columns -->
<tr>
<th>STATE</th>
<th>CALLID</th>
<th>COLLECTED</th>
<th>ZONE</th>
</tr>
</thead>
<!-- -->
<tbody class="callView">
<tr>
<td>0</td>
<td>10001</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>10002</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>10003</td>
<td>spring</td>
<td>1</td>
</tr>
</tbody>
</table>
最佳答案
除了向每个单元格添加 onclick
事件之外,您还可以将其添加到表格中,并从参数中获取必要的信息:
var tbl = document.getElementById("recordingTable");
tbl.onclick = function(e)
{
console.log(e.target.innerHTML);
console.log(e.target.cellIndex);
console.log(e.target.parentElement.rowIndex);
}
JsFiddle:https://jsfiddle.net/19qfsxr9/14/
关于javascript - 如何获取点击表格的行列信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35934664/