如何在使用ajax时自动隐藏flash消息

med*_*zid 1 flash ajax jquery ruby-on-rails

我使用ujs发送ajax请求,在我的destroy.js.erb文件中,我有以下代码:

$("#wrapper").prepend('<div class="flash-notice"><%= escape_javascript(flash.discard(:notice)) %></div>');
Run Code Online (Sandbox Code Playgroud)

上面的行显示使用ajax时的flash通知消息,我想要的是在延迟后自动隐藏此flash消息

($(".flash-notice").delay(600).fadeOut(300);)不起作用,因为消息是动态添加的,而不是存在于DOM中

Bil*_*han 6

在普通的html模板中用div包装你的flash消息

<div id='notice'>
</div>
Run Code Online (Sandbox Code Playgroud)

然后,在js模板中

$('#notice').html("<%=j msg %>").show().fadeOut(4000)
Run Code Online (Sandbox Code Playgroud)

msg上面的方法将包含完整的html<div class='flash'>...

然后,在淡出后,#notice仍然在DOM中display:none,您可以随时再次使用它.

PS您可以使用帮助程序处理Flash消息,这样您就不需要在模板中对其进行硬编码.

def flash_output(text, type)
  content_tag :div, class: "flash-#{type}" do
    text
  end
end
Run Code Online (Sandbox Code Playgroud)

所以上面的js模板可以写入

$('#notice').html("<%=j flash_output(msg, 'notice') %>").show().fadeOut(4000)
Run Code Online (Sandbox Code Playgroud)