3

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.

escapesequence
  • 202
  • 4
  • 12
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

1 Answers1

3

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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101