2009-03-02 5 views
15

J'ai besoin de trouver la position d'un élément enfant.Comment obtenir la position d'un élément enfant

j'ai une table et quand un td est cliqué, je veux la position de la td (0,1 ou 2)

<table> 
<tr> 
<td> 

</td> 
<td> 

</td> 
<td> 

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

et un script comme celui-ci

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

Trick l'élément parental dans la fixation d'un système de localisation GPS. –

+1

@AdamDavis Cette solution ne fonctionne que lorsque l'élément enfant atteint l'adolescence. – Neil

Répondre

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: Je l'ai testé, et cela fonctionne

0

Juste pour référence, et c'est bon

<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

Questions connexes