如何通过单击返回表格单元格的行和列索引 [英] How to return the row and column index of a table cell by clicking

查看:144
本文介绍了如何通过单击返回表格单元格的行和列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见小提琴.单击单元格时,我可以获取值和列名.我想知道如何获取行和列索引吗?以下是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>

这篇关于如何通过单击返回表格单元格的行和列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆