简体   繁体   中英

Table tr and td have weird click events

I have a table like the following snippet shows.

 $(function(){ $('.table-price td.go-to-price').click(function(){ console.log($(this).attr('data-link')); goToLink($(this).attr('data-link')); }) $('.table-price tr.go-to-product').click(function(){ console.log($(this).attr('data-link')); goToLink($(this).attr('data-link')); }) }) function goToLink(url) { location.href = url ; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table-price"> <tr class="go-to-product" data-link="http://tahrircenter.com/product/correction-pens/url"> <td>1</td> <td>10013</td> <td>عنوان</td> <td></td> <td>10</td> <td> <p class="">0</p> </td> <td class="go-to-price" data-link="http://tahrircenter.com/product/correction-pens/url#price-change" > <a href="http://tahrircenter.com/product/correction-pens/url#price-change">IMAGE</a> </td> </tr> </table> 

The tr has a data-link attribute and the last td has a different data-link attribute, but when I click on the tr element, the website navigates to url of td element, instead of the tr element.

You need to stop the click event from bubbling when you click on the td using stopPropagation() , like :

$('.table-price td.go-to-price').click(function(e){
  e.stopPropagation();

  console.log($(this).attr('data-link'));
  goToLink($(this).attr('data-link'));
})

Hope this helps.

 $(function(){ $('.table-price td.go-to-price').click(function(e){ e.stopPropagation(); console.log($(this).attr('data-link')); goToLink($(this).attr('data-link')); }) $('.table-price tr.go-to-product').click(function(e){ e.stopPropagation(); console.log($(this).attr('data-link')); goToLink($(this).attr('data-link')); }) }) function goToLink(url) { location.href = url ; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table-price"> <tr class="go-to-product" data-link="http://tahrircenter.com/product/correction-pens/url"> <td>1</td> <td>10013</td> <td>عنوان</td> <td></td> <td>10</td> <td> <p class="">0</p> </td> <td class="go-to-price" data-link="http://tahrircenter.com/product/correction-pens/url#price-change" > <a href="http://tahrircenter.com/product/correction-pens/url#price-change">IMAGE</a> </td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM