2009-03-02 49 views
15

我需要找到子元素的位置。我如何獲得子元素的位置

我有一個表,並在單擊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> 
+5

特技親元件成附接GPS跟蹤系統。 – 2009-03-02 16:12:47

回答

35
<script> 
$("td").click(function(){ 
    //how do i get the position of the td? 
    alert("column " + $(this).parent().children().index(this) + " is clicked") 
}); 
</script> 
腳本

編輯:我測試過了,它能正常工作

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> 

refer here