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

问题描述:

请参见小提琴.单击单元格时,我可以获取值和列名.我想知道如何获取行和列索引吗?以下是js代码,

Please see the fiddle. When I click the cell, I can get the value and the column name. I wonder how can I get the row and column index instead? Following is the js code,

<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>

最好是在这里使用closest

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

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

<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>