您好,有一个包含很多行的表格
第一行有<th>
s 那么接下来的所有行都包含 <td>
如果我使用下面的脚本并单击第一行 <td>
我收到一条警告,提示 1。如何让它显示零而不减一。我认为使用“has(td)”会起作用吗?
$('td').click(function(){
var s = $(this).parents('table tr:has(td)').index();
alert(s);
});
<table border="1" width="400px" height="200px">
<tr>
<th></th><th></th><th></th><th></th><th></th>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td> if I click here it must alert 0
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td> if I click here it must alert 1
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td> if I click here it must alert 2
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td> if I click here it must alert 3
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td> if I click here it must alert 4
</tr>
</table>
最佳答案
将 a 选择器传递给 .index()
以过滤掉同级
$('td').click(function(){
var s = $(this).parent().index('tr:has(td)');
alert(s);
});
关于javascript - 获取表行中 tds onclick 的从零开始的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11859356/