【问题标题】:How to get cells (<td>) x and y coordinate in table using jQuery?如何使用 jQuery 在表格中获取单元格 (<td>) x 和 y 坐标?
【发布时间】:2010-12-19 00:41:24
【问题描述】:

我正在寻找一种在表格中获取单元格 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);
});

我想,最简单的方法是在后端创建表格时向每个单元格(&lt;td class="p-5x7"&gt; 等)添加 innerHTML、ID 或 CSS 类,然后解析它,然后点击返回,但是有什么办法可以完全基于 DOM 获取这些坐标?

【问题讨论】:

    标签: javascript jquery coordinates


    【解决方案1】:

    DOM 2 级 HTML cellIndex:

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

    【讨论】:

      【解决方案2】:

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-14
        • 1970-01-01
        • 1970-01-01
        • 2018-09-27
        相关资源
        最近更新 更多