如何通过单击返回表格单元格的行和列索引

新手上路,请多包涵

请看 小提琴。当我点击单元格时,我可以获得值和列名。我想知道如何获取行和列索引?以下是js代码,

 <script type="text/javascript">

    $(document).ready(function(){
        $('#example tbody').on( 'click', 'td', function () {
            alert('Data:'+$(this).html().trim());
            alert('Row:'+$(this).parent().find('td').html().trim());
            alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim());
        });
    });

</script>

原文由 WCMC 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 869
2 个回答

最好的可能是在这里使用 closest

对于集合中的每个元素,通过测试元素本身并向上遍历其在 DOM 树中的祖先来获取与选择器匹配的第一个元素。

 <script type="text/javascript">

    $(document).ready(function(){
        $('#example tbody').on( 'click', 'td', function () {
            alert('Row ' + $(this).closest("tr").index());
            alert('Column ' + $(this).closest("td").index());
        });
    });

</script>

原文由 Axalix 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种 Native JS 方法是使用 TableData 属性,在使用表格元素时可以找到这些属性。 For example, cellIndex will return the column index of a td element and rowIndex will return the index of a tr element.这两个属性将大大简化我们的代码,如以下代码所示。

 const cells = document.querySelectorAll('td');
cells.forEach(cell => {
  cell.addEventListener('click', () =>
    console.log("Row index: " + cell.closest('tr').rowIndex + " | Column index: " + cell.cellIndex));
});
 <table>
  <tr>
    <td>0:0</td>
    <td>0:1</td>
    <td>0:2</td>
    <td>0:3</td>
  </tr>
  <tr>
    <td>1:0</td>
    <td>1:1</td>
    <td>1:2</td>
    <td>1:3</td>
  </tr>
  <tr>
    <td>2:0</td>
    <td>2:1</td>
    <td>2:2</td>
    <td>2:3</td>
  </tr>
</table>

原文由 Alain Cruz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题