表tr和td有奇怪的点击事件

时间:2017-07-27 16:02:52

标签: javascript jquery html jquery-click-event

我有一个类似以下代码段的表格。

$(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>

tr具有data-link属性,而最后td具有不同的data-link属性,但当我点击tr元素时,该网站导航到td元素的网址,而不是tr元素。

1 个答案:

答案 0 :(得分:3)

当您使用 stopPropagation() 点击click时,您需要阻止td事件冒泡,例如:

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

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

希望这有帮助。

&#13;
&#13;
$(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 ;
}
&#13;
<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>
&#13;
&#13;
&#13;