javascript - 如何获取点击表格的行列信息

标签 javascript html

我有以下 fiddle - 我正在测试获取表中数据的概念。目前,当我单击单元格时,我可以获取特定单元格中显示的值。

此外,我希望能够获取单击单元格的行索引和列索引。这里有人知道如何做到这一点吗?

Link to 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/

相关文章:

javascript - 从 FastAPI 获取文件时如何使用浏览器缓存?

Javascript:新图像未出现在 Firefox 和 IE 中

javascript - 如何每秒增加数据库中的值

javascript - Html 和 js 文件/OS X

html - Mozilla 没有显示正确的字体

html - Bootstrap 3 导航栏不会切换到 "mobile"版本

javascript - touchstart 事件无法在 IPAD 中使用 Animate CC JavaScript

Javascript:数组加数字

javascript - 使用jquery获取<tag>的内容

javascript - 使 Textarea 足以完全适合 maxLength 属性