目前,如果用户未登录,当用户按下按钮时,它会正确显示警报,但接着进行实际提交。我希望它显示警报,但然后保持在当前页面(即不直接到提交页面)。我怎么能这样做?
<% 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 :(得分: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的更多信息,这非常有趣(并且知道很重要)