This is done very easily using the target
property of the event
object:
$('#mytable').click(function(e) {
var tr = $(e.target).parent('tr');
var x = $('tr', this).index(tr);
var y = tr.children('td').index($(e.target));
alert(x + ',' + y);
});
This approach allows you to only bind 1 event handler to the entire table and then figure out which table cell was clicked. This is known as event delegation and can be much more efficient in the right situation, and this one fits the bill. Using this you avoid binding an event to each <td>
, and it does not require hard-coding coordinates. So, if your table looks like this:
<table id='mytable'>
<tr>
<td>hi</td>
<td>heya</td>
</tr>
<tr>
<td>boo</td>
<td>weee</td>
</tr>
</table>
It will alert the coordinates on click. You can do whatever with that. :)
If you find performance to be too slow (depending on just how large your table is) you would then have to resort to hardcoding or a combination of the two, maybe only hard coding the <tr>
index, as that would be the slowest to get, and then getting the <td>
index dynamically. Finally, if all this coordinate business is completely unnecessary and what you really just wanted was a reference to the clicked <td>
, you would just do this:
$('#mytable').click(function(e) {
var td = $(e.target);
// go crazy
});