jQueryでどこのセルが押されたか判定する方法

テーブルタグ無いのどこのセルが押されたかが知りたかったので、その方法を調べてみた

こんなテーブルを用意して、その中の何番目のセルが押されたかを調べるには

<table class="target_table">
	<tr>
		<td>
			1個目
		</td>
		<td>
			2個目
		</td>
		<td>
			3個目
		</td>
		<td>
			4個目
		</td>
	</tr>
</table>

$().click(function(){}) の第1引数でイベントオブジェクトを取得できるので、そのオブジェクトのindex()を取得すれば大丈夫

$(function() {
	$('.target_table td').click(function(event){
		// currentTarget のindex()を取得
		alert(
			$(event.currentTarget).index()
		);
		// target でも大丈夫だった
		alert(
			$(event.target).index()
		);
	});
});

indexは0から割り振られているので、上記のテーブルの場合は「1個目」のセルが 0 になる