How to exclude a subitem from a parent click event?

I had a problem when there is a click event in a table row, but when a user clicks a link in one of the cells of a table row, I do not want the row click event to fire.

Imagine a case where a table cell has a link inside it and usually clicks on empty areas of any of the rows in the table (for example, not links), causing some actions, such as merging and aligning the accordion / string.

What happens is that the click event below is triggered, after which the link is executed (the intended action).

I need to prevent href clicking inside a from triggering the click click action for the string tr.title (for example, the warning should not fire, and the link should be executed).

This jQuery code sets up click events for the title bar (for example, all THs on this line, any cells, etc.).

$(document).ready(function() { $(".report tr.title-row").click(function() { alert('I am firing!'); }); 

Here is the same HTML this applies to:

 <table width="100%" cellspacing="0" cellpadding="0" border="0" class="report"> <tbody> <tr class="title-row"> <th width="340"><span class="title">Test</span> </th> <th width="130" class="center-cell">Test</th> <th width="90" class="status"></th> <th></th> <th width="160"> <a target="_self" href="http://www.google.com" class="link-class sub-class">I am triggering the TR click event</a> </th> </tr> <tr> <td class="sub-row" colspan="5"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td><strong>SubRow</strong> </td> <td width="90" class="status"><span class="sub">Sub</span> </td> <td width="120"></td> <td width="160"><a title="Continue" href="http://www.yahoo.com">Something</a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> 
+6
source share
2 answers

You can check the target line click and run only the code if the target is not a <a> tag:

 $(".report tr.title-row").click(function(event) { if( ! $(event.target).is('a') ){ alert('I only fire when A not clicked!'); } }); 
+5
source

just stop the event bubbles in the line

 $(".report tr.title-row").click(function() { alert('I am firing!'); }); $(".report tr.title-row a").click(function(ev){ // link clicked // so something ev.stopPropagation(); // stop triggering the event to the table row }); 

btw ... for better code, just use on instead of the name of the event handler

 $(".report tr.title-row").on( 'click', function() { alert('I am firing!'); }); $(".report tr.title-row a").( 'click', function(ev){ // link clicked // so something ev.stopPropagation(); // stop triggering the event to the table row }); 
+2
source

All Articles