jQuery Table Row Click Event also firing when i click a link

Viewed 34432

Here is what i have so far, getting the row number is working great but i need to make it so that when i click on the link in the table, it doesnt fire the code inside the function.

<table>
  <tr class="row">
    <td>A</td>
    <td><a class="link" href="foo.html">Foo</a></td>
  </tr>
  <tr class="row">
    <td>B</td>
    <td><a class="link" href="Bar.html">Bar</a></td>
  </tr>
</table>


<script>
$(function(){
    $('.row:not(.link)').click(function(){
        var $row = $(this).index();
    });
});
</script>
8 Answers

Just add: if (e.target.tagName == 'A') return; to row click and Link element will use its own logic.

Here is more detailed example:

$("#table tr").click(function(e) {

    // Skip if clicked on <a> element
    if (e.target.tagName == 'A') return;

    // Logic for tr click ...

});

Also can be usable (especially if you use href with span or other nested items in href):

    $(".row").click(function(e) {
        var hasHref = $(e.target).closest('td').find('a').length;

        if (! hasHref) {
            window.document.location = $(this).data("href");
        }
    });
Related