2016-02-07 14 views
1

我發現我的第一個答案how to make a whole row in a table clickable as a link?,但現在出現了一個新問題:如何排除在JavaScript中點擊一行中的<a>標籤?

使用

<tbody> 
    <tr class='clickable-row' data-href='url://link-for-first-row/'> 
     <td>Blah Blah</td> 
     <td>1234567</td> 
     <td>£158,000</td> 
    </tr> 
    <tr class='clickable-row' data-href='url://some-other-link/'> 
     <td>More money</td> 
     <td>1234567</td> 
     <td><a href="url://somewhere-else-than-the-row">£800,000</a></td> 
    </tr> 
</tbody> 

jQuery(document).ready(function($) { 
    $(".clickable-row").click(function() { 
     window.document.location = $(this).data("href"); 
    }); 
}); 

使我陷入困境與最後一個環節爲「 url:// somewhere-else-the-row',特別是當我使用method =「delete」屬性的鏈接時,「你確定嗎?」彈出,但是,我不想讓window.location運行。那麼,如何從window.document.location參考中排除<a>元素上的單擊?

回答

0

大多數活動泡了DOM樹,你實際點擊可能不是一個處理程序設置上的節點。

  • 在處理機(通常)this指的是其所連接的節點
  • event.target(其中event是處理程序的第一個參數)是指節點點擊

檢查是否在解析位置之前,點擊的目標是或者是<a>的後代。

jQuery(document).ready(function($) { 
    $(".clickable-row").click(function (e) { 
     if ($(e.target).closest('a').length) // if <a> or decendant of <a> 
      return; // do nothing 
     // otherwise 
     window.document.location = $(this).data("href"); 
    }); 
}); 
+0

感謝這兩者,我更喜歡這個解決方案,因爲我在rails上使用ruby,並且我可以簡單地使用link_to helper。我使用<%= link_to glyph('remove'),admin_person_path(admin_person),方法:: delete,data:{confirm:'你確定嗎? }%>爲其中一個鏈接,所以這個解決方案是easyer使用。 – Martin

2

JavaScript中的事件傳播了dom層次結構。你可以在這裏閱讀更多關於這個:What is event bubbling and capturing?

至於你的問題,你可能想看看jquery的event.stopPropagation,以防止點擊事件,從提高DOM和觸發超過1事件。見http://www.w3schools.com/jquery/event_stoppropagation.asp

代碼示例:

<tbody> 
<tr class='clickable' data-href='url://link-for-first-row/'> 
    <td>Blah Blah</td> 
    <td>1234567</td> 
    <td>£158,000</td> 
</tr> 
<tr class='clickable' data-href='url://some-other-link/'> 
    <td>More money</td> 
    <td>1234567</td> 
    <td><span class="clickable" data-href="url://somewhere-else-than-the-row">£800,000</span></td> 
</tr> 

jQuery(document).ready(function($) { 
    $(".clickable-row").click(function(event) { 
     event.stopPropagation(); 
     window.document.location = $(this).data("href"); 
    }); 
}); 

我加2名更改您的代碼:

  • <a>標籤的相反,我用了一個<span>標籤與「可點擊」類
  • 對於事件處理程序,我添加了對jquery的event.stopPropagation的調用,以確保只調用第一個處理程序。