2009-03-02 2 views
15

Мне нужно найти положение дочернего элемента.Как получить положение дочернего элемента

У меня есть таблица и когда тд нажата, я хочу позицию тд (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 слежения. –

+1

@AdamDavis Это решение работает только до тех пор, пока дочерний элемент не достигнет подросткового возраста. – Neil

ответ

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