2013-04-29 84 views
0

此刻,如果用戶未登錄,當用戶按下按鈕時,它會正確顯示警報,但會繼續提交。我希望它顯示警報,但留在當前頁面(即不直接到提交頁面)。我怎樣才能做到這一點?在點擊提交按鈕後顯示提醒,但實際沒有提交

<% if current_user %> 
     <div class="form-actions"> 
      <%= f.button :submit, :class => "btn btn-info btn-large" %> 
     </div> 
    <% else %> 
     <%= f.button :submit, :class => "btn btn-info btn-large", :onclick => 'alert("You need to be logged in to add comments!")'%> 
    <% end %> 
+0

嘗試在onclick處理程序中返回false – jul 2013-04-29 23:13:15

+1

@jul:返回'false'不會阻止事件傳播/冒泡...在我的答案中閱讀鏈接以獲取更多詳細信息 – 2013-04-29 23:35:29

回答

1

添加JS功能的頁面,這樣寫:

<%= f.button :submit, :class => "btn btn-info btn-large", :onclick => 'submitAlert(event)'%> 

的JS函數看起來是這樣的:

function submitAlert(e) 
{ 
    e = e || window.event; 
    alert('You need to be logged in to add comments!'); 
    if (e.preventDefault) 
    {//most browsers 
     e.preventDefault(); 
     e.stopPropagation(); 
    } 
    e.returnValue = false; 
    e.cancelBubble= true; 
} 

瞭解更多關於停止事件here這是相當有趣(並且很重要)

+0

完美,謝謝 – tessad 2013-04-29 23:36:05