Exclude button from OnClick event listener

A really simple jquery question here that I haven't solved yet. I have the following html table

<table id="table-1"> <tr> <td>Value 1</td> <td>Value 2</td> <td> <button id="btn-1" value="Go"></button> </td> </tr> </table> 

I have the following event listener when a table button is clicked

 $("table-1 tr").on( 'click', function(e){ if(button was clicked){ //do some stuff } else { //do different stuff } } ); 

I would like this event listener to fire whenever a table row is selected, unless my button is an item click. I tried to use :not and .not() , but no luck. Any ideas?

+5
source share
4 answers

Based on your example, where you want to catch the element type.

 $("#table-1 tr").on('click', function (e) { var elementType = $(e.target).prop('nodeName'); if (elementType == 'BUTTON') { console.log('buttonClick'); } else { console.log(elementType); }; }); 

http://jsfiddle.net/ymy9cn71/

+3
source

Use event.stopPropagation () to prevent event bubbles from parent elements.

 $('#btn-1').click(function(event){ event.stopPropagation(); }) 
+3
source

What if you specifically set up an event listener? The most specific rule must be applied. Therefore, if you click on a row, the row event will fire, if you click on a button, then the button event will fire FIRST, and then the parent will fire. This way you can use a simple variable to check if the button has been checked.

Var gContext;

 $("#btn-1"). on('click', function() { gContext = true }); $("table-1 tr").on( 'click', function(e){ if(button was clicke$("table-1 tr").on( 'click', function(e){ if(gContext === true){ //do some stuff } else { //do different stuff } } );d){ //do some stuff } else { //do different stuff } } ); 
  • did it on my phone, I hope that it is correctly drawn up.
+1
source

The following code checks the tag name of the target to see which part of the tr element has been clicked.

 $('table').on('click', 'tr', function (e) { var i = $('table tr').index(this); var tag = e.target.tagName.toLowerCase(); if (tag === 'button') { alert('go #' + i); } else { alert('select row #' + i); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Value 1</td> <td>Value 2</td> <td><button>Go</button></td> </tr> <tr> <td>Value 1</td> <td>Value 2</td> <td><button>Go</button></td> </tr> </table> 
+1
source

All Articles