开发者

How to get cells (<td>) x and y coordinate in table using jQuery?

开发者 https://www.devze.com 2022-12-11 22:16 出处:网络
I\'m looking for a good way to get cells X-Y position in a table. (do not confuse it with css-position, I am looking for X and Y coordinate in Cartesian coordinate system).

I'm looking for a good way to get cells X-Y position in a table. (do not confuse it with css-position, I am looking for X and Y coordinate in Cartesian coordinate system).

As we know, we can get particular cell in a table using ex: $('#grid')[0].rows[5].cells[7].

But, what if I want to get the value 5x7 when I click 开发者_开发百科on particular cell, i.e:

$('#grid td').click(function(){
   alert("My position in table is: " + myPosition.X + "x" + myPosition.Y);
});

I guess, the easiest way is to add innerHTML, ID or CSS class to every cell (<td class="p-5x7"> etc.) when creating table in back end, then parse it, and return on click, but is there any way to get these coordinates based purely on DOM?


DOM Level 2 HTML cellIndex:

alert('My position in table is: '+this.cellIndex+'x'+this.parentNode.rowIndex);


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>

0

精彩评论

暂无评论...
验证码 换一张
取 消