2014-03-12 44 views
0

假設我有一個錶行是這樣的:在Rails中,點擊可點擊行中的圖標時,如何選擇性地停止傳播?

NAME AGE ACTION (icons) 
Alice 30 [edit] [delete] 
Bob  30 [edit] [delete] 

當我點擊一排,我想被帶到用戶的顯示視圖:

$("tr.user_row").click ->  
    window.location = $(this).data("link") 

除了當我點擊的一個圖標。在這種情況下,我希望點擊事件在到達行級鏈接並重新定位之前停止。

此外,刪除圖標應用了一個確認動作:

<%= link_to image_tag("delete.png", alt: "delete", title: "delete"), 
     user_path(@user), 
     remote: true, method: :delete, 
     data: { confirm: sprintf("You sure you want to delete this user?") }, 
     class: "action-link" 
%> 

一般情況下我有這樣的事情在users.js.coffee

$("tr.user_row a").click (e) -> 
    e.stopPropagation() 

但如果我這樣做,在這裏,它阻止從發射確認消息,我不能 刪除用戶。

有沒有辦法來安排這一點,以便點擊行重定向,除非點擊編輯或刪除圖標刪除圖標保留其所需的行爲?

+0

爲什麼不把點擊事件放在你想點擊而不是整個tr的td上? –

+0

@MaxWilliams在大多數情況下,這可能會足夠接近。 – klenwell

回答

0

下面是我如何解決這個問題。 (這是Rails的4.0,但應在早期版本的工作了。)

首先,我標記的每個圖標圖像與類stop-prop

<%= link_to image_tag("delete.png", alt: "delete", title: "delete", 
         class: "stop-prop"), 
     user_path(@user), 
     method: :delete, 
     remote: true, 
     data: { confirm: "Are you sure you want to delete this user?" }, 
     class: "action-link" 
%> 

然後在我的users.js.coffee文件,我更換了這一點:

$("tr.user_row").click ->  
    window.location = $(this).data("link") 

$("tr.user_row a").click (e) -> 
    e.stopPropagation() 

與此:

# Make user row links clickable but stop propagation when icons clicked 
$("tr.user_row").click (e) -> 
    # Check e.target ("the DOM element that initiated the event" per jQuery 
    # docs) for stop-prop class to stop event from propagating. 
    ok_to_propagate = ! $(e.target).hasClass('stop-prop'); 

    if ok_to_propagate 
     window.location = $(this).data("link") 

$(e.target)將是「發起事件的DOM元素」,即當點擊該圖標時,將具有stop-prop類的圖像標籤應用於該圖標。

相關問題