2013-04-29 88 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