我有一个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。
我也试过以下方法获取行索引,但同样的问题
row = $(this).parent().parent().children().index($(this).parent());
row = parseInt($(this).parent().index()) ;
亲切的帮助。
姆兰
答案 0 :(得分:0)
<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>