2017-07-27 85 views
3

我有一個表,如下面的片段顯示。表tr和td有奇怪的點擊事件

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

trdata-link屬性和最後td有不同的data-link屬性,但是當我點擊tr元素,網站導航,而不是到URL td元素, tr元素。

+0

使用事件stopPropagation –

回答

3

您需要冒泡,當你點擊td使用stopPropagation()停止click事件,如:

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

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

希望這有助於。

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

+0

更新我的網站,但它不工作。 http://tahrircenter.com/ –

+0

請您評論'location.href = url;'所以我們可以看到'console.log()'顯示的是什麼.. –

+0

我評論'location.href = url;'並刪除'來自'a'的href'; –