我需要找到子元素的位置。
我有一张桌子,当点击一个td时,我想要td的位置(0,1或2)
<table>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
和这样的脚本
<script>
$("td").click(function(){
//how do i get the position of the td?
alert("column " + columnPosition + "is clicked")
});
</script>
答案 0 :(得分:35)
<script>
$("td").click(function(){
//how do i get the position of the td?
alert("column " + $(this).parent().children().index(this) + " is clicked")
});
</script>
编辑:我测试了它,并且它可以正常工作
答案 1 :(得分:0)
仅供参考,这很好
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<div>Fourth div</div>
<script>
$( "div" ).click(function() {
// `this` is the DOM element that was clicked
var index = $( "div" ).index( this );
$( "span" ).text( "That was div index #" + index );
});
</script>