2009-03-02 15 views
15

Ich muss die Position eines Kindelements finden.Wie bekomme ich die Position eines Kindelements

Ich habe eine Tabelle, und wenn ein td geklickt wird, möchte ich die Position des td (0,1 oder 2)

<table> 
<tr> 
<td> 

</td> 
<td> 

</td> 
<td> 

</td> 
</tr> 
</table> 

und ein Skript wie diese

<script> 
$("td").click(function(){ 
    //how do i get the position of the td? 
    alert("column " + columnPosition + "is clicked") 
}); 
</script> 
+5

Trick des parentale Element in einem GPS-Tracking-System angebracht wird. –

+1

@AdamDavis Diese Lösung funktioniert nur, bis das Kindelement die Adoleszenz erreicht. – Neil

Antwort

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

edit: Ich habe es getestet, und es funktioniert

0

Nur als Referenz, und das ist gut

<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

Verwandte Themen