Brandon Brandon - 3 months ago 16
HTML Question

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

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>

Answer

The selector .row:not(.link) will select all elements that have a class "row" and don't have the class "link", which is not what you are looking for.

You need to use event.stopPropagation within the click event of the a.link elements so that the click event is not propagated to the parents, which includes row.

Try this:

<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').click(function(){         
            var $row = $(this).index();     
        }); 
        $('.row .link').click(function(e){
            e.stopPropagation(); 
        });
    }); 
</script>
Comments