我使用ujs发送ajax请求,在我的destroy.js.erb文件中我有以下代码:
$("#wrapper").prepend('<div class="flash-notice"><%= escape_javascript(flash.discard(:notice)) %></div>');
上面的行在使用ajax时显示一条flash通知消息,我想要的是在延迟后自动隐藏此flash消息
( $(".flash-notice").delay(600).fadeOut(300);
) 不起作用,因为消息是动态添加的并且不存在于 DOM 中
最佳答案
在普通的 html 模板中使用 div 包装您的 Flash 消息
<div id='notice'>
</div>
然后,在js模板中
$('#notice').html("<%=j msg %>").show().fadeOut(4000)
msg
上面的方法将包含 <div class='flash'>...
的完整 html
然后,淡出后,#notice
仍在 DOM 中,但 display:none
,您可以随时再次使用。
附注您可以使用助手来处理 Flash 消息,这样您就不需要在模板中对其进行硬编码。
def flash_output(text, type)
content_tag :div, class: "flash-#{type}" do
text
end
end
所以上面的js模板就可以写成
$('#notice').html("<%=j flash_output(msg, 'notice') %>").show().fadeOut(4000)
关于jquery - 如何在使用ajax时自动隐藏flash消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19371937/