Как я могу получить позицию дочернего элемента - PullRequest
15 голосов
/ 02 марта 2009

Мне нужно найти позицию дочернего элемента.

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

Ответы [ 2 ]

35 голосов
/ 02 марта 2009
<script>
$("td").click(function(){
  //how do i get the position of the td?
  alert("column " + $(this).parent().children().index(this) + " is clicked")
});
</script>

редактировать: я проверил, и он работает

0 голосов
/ 07 января 2014

Только для справки, и это хорошо

<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>

см. Здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...