2016-03-11 22 views
0

我有以下小提琴 - 我在这里测试了一个获取表格中数据的概念。此刻,当我点击单元格时,我可以获得显示在特定单元格中的值。如何获取点击表格的行和列信息

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

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++) 
 
     \t \t 
 
      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>

回答

1

您可以通过在函数中使用添加onclick事件,你可以把它添加到每个细胞的

cel.rowIndex 
cel.cellIndex 

2

欧洲工商管理学院获得表,并从参数获得neccesary信息:

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/