Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is done very easily using the <code>target</code> property of the <code>event</code> object:</p> <pre><code>$('#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); }); </code></pre> <p>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 <code>&lt;td&gt;</code>, and it does not require hard-coding coordinates. So, if your table looks like this:</p> <pre><code>&lt;table id='mytable'&gt; &lt;tr&gt; &lt;td&gt;hi&lt;/td&gt; &lt;td&gt;heya&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;boo&lt;/td&gt; &lt;td&gt;weee&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>It will alert the coordinates on click. You can do whatever with that. :)</p> <p>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 <code>&lt;tr&gt;</code> index, as that would be the slowest to get, and then getting the <code>&lt;td&gt;</code> index dynamically. Finally, if all this coordinate business is completely unnecessary and what you really just wanted was a reference to the clicked <code>&lt;td&gt;</code>, you would just do this:</p> <pre><code>$('#mytable').click(function(e) { var td = $(e.target); // go crazy }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload