【问题标题】:Jquery returning same index for last row and second last row of html tableJquery为html表的最后一行和倒数第二行返回相同的索引
【发布时间】:2015-09-23 08:32:39
【问题描述】:

我有一个html表格,如下

  <div class="filesList">
                        <table id="tblFiles">
                            <tr style=" ">
                                <td class="td1"> File Name1 </td>
                                <td class="td2"></td>
                                <td class="td3" > - </td>
                            </tr>
                            <tr style=" ">
                                <td class="td1"> File Name2 </td>
                                <td class="td2"></td>
                                <td class="td3" > - </td>
                            </tr>
                            <tr style=" ">
                                <td class="td1"> File Name3 </td>
                                <td class="td2"></td>
                                <td class="td3"  > - </td>
                            </tr>

                        </table>
                    </div>

现在,我正在使用此代码来获取点击行的索引。即用户点击一行的第三列,我得到点击行的索引。

$('#tblFiles').on('click', "td:nth-child(3)", function (e) {
    var col = $(this).parent().children().index($(this));
    var row = $(this).closest('tr').index();  
    alert('Row#: ' + row + ', Column#: ' + col);
 });

我遇到的问题是,它返回最后一行和倒数第二行的相同行索引。 即它为第 2 行和第 3 行返回 2。

我也尝试了以下方法来获取行索引,但同样的问题

 row = $(this).parent().parent().children().index($(this).parent());

 row = parseInt($(this).parent().index()) ;

请帮忙。 伊姆兰

【问题讨论】:

标签: jquery html css-tables


【解决方案1】:
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

</head>


<body>
<table id="tblFiles" cellpadding="5" border="2">
<tr style=" ">
                                <td class="td1"> File Name1 </td>
                                <td class="td2"></td>
                                <td class="td3" > - </td>
                            </tr>
                            <tr style=" ">
                                <td class="td1"> File Name2 </td>
                                <td class="td2"></td>
                                <td class="td3" > - </td>
                            </tr>
                            <tr style=" ">
                                <td class="td1"> File Name3 </td>
                                <td class="td2"></td>
                                <td class="td3"  > - </td>
                            </tr>
</table>
<script>

$('#tblFiles').on('click', "td", function (e) { 
    var row = parseInt($(this).parent().index())+1;
    var column = parseInt($(this).index())+1;  
    alert('Row#: ' + row + ', Column#: ' + column );
 });

</script>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2018-10-29
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多