我正在寻找一种在表格中获得单元格X-Y位置的好方法。(不要将它与css-position混淆,我正在寻找笛卡尔坐标系中的X和Y坐标)。
正如我们所知道的,我们可以使用ex:$('#grid')[0].rows[5].cells[7]来获取表格中的特定单元格。
但是,如果我想要在单击特定单元格时获得值5x7,例如:
$('#grid td').click(function(){
alert("My position in table is: " + myPosition.X + "x" + myPosition.Y);
});我想,最简单的方法是向每个单元格(<td class="p-5x7">等)添加innerHTML、ID或CSS类。在后端创建表时,解析它,然后单击返回,但是有没有办法完全基于DOM来获得这些坐标呢?
发布于 2009-11-21 21:40:37
DOM Level 2 HTML cellIndex
alert('My position in table is: '+this.cellIndex+'x'+this.parentNode.rowIndex);发布于 2017-11-02 23:57:20
window.onload = function () {
document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
alert("My position in table is: " + e.target.parentElement.rowIndex + "x " + e.target.cellIndex + "y");
}, false);
}tr, td {
padding: 0.6rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}<table id="grid">
<tr>
<td>0, 0</td>
<td>0, 1</td>
<td>0, 2</td>
</tr>
<tr>
<td>1, 0</td>
<td>1, 1</td>
<td>1, 2</td>
</tr>
</table>
https://stackoverflow.com/questions/1775466
复制相似问题