動かざることバグの如し

近づきたいよ 君の理想に

Jqueryでクリックされたテーブルの位置(X行X列目)を取得する

普通にこんな感じのテーブルがあったとして

<table border="3">
<tr>
<td>データセル1-1</td>
<td>データセル1-2</td>
<td>データセル1-3</td>
</tr>
<tr>
<td>データセル2-1</td>
<td>データセル2-2</td>
<td>データセル2-3</td>
</tr>
<tr>
<td>データセル3-1</td>
<td>データセル3-2</td>
<td>データセル3-3</td>
</tr>
</table>

以下のようにすると「Row: 2, Column: 2 」のようにクリックされたセルの位置を取得できる

$('td').click(function(){
    //縦
    var row = $(this).closest('tr').index();
    //横
    var col = this.cellIndex;
    console.log('Row: ' + row + ', Column: ' + col);
});

ちなみにクリックされたセルの文字列を取得するには

$(this).text();
  • row 縦
  • column 横