2012-08-08 85 views
0

喜有,有许多行得到TDS的从零开始的索引的onclick在表行

第一行有<th>当时的所有下列各行包含一个表<td>小号

如果我使用下面的脚本并点击第一行<td> s在其中我得到一个警告说:1.我怎么说它与零减去一。我认为使用“有(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> 
+0

错误标记。你写的文字超出'​​'标签 – diEcho 2012-08-08 07:09:33

+3

当然'$(this).parent()。index() - 1'比任何带有':has'或':contains'的选择器或任何其他解决方案。我发现它也更容易阅读。 (但是你的代码不起作用,因为没有参数的'.index()'返回元素索引与DOM中的同胞相关,而不是与jQuery对象中的其他元素有关。) – nnnnnn 2012-08-08 07:23:22

回答

4

传递一个选择器.index()过滤掉兄弟姐妹

$('td').click(function(){ 
    var s = $(this).parent().index('tr:has(td)'); 
    alert(s); 
});​ 

http://jsfiddle.net/nAhE3/

相关问题