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

标签 jquery ruby-on-rails ajax flash

我使用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/

相关文章:

javascript - 无法隐藏 HTML 表格

ruby-on-rails - 参数缺失或值为空 : center

ruby-on-rails - 嵌套模型、表单和 date_select FormHelper 集成

javascript - 停用 Smarty Streets 功能

jquery - 使用 JSZip 下载图像会导致浏览器崩溃

ruby-on-rails - 在 Rails 中创建 2 个具有 has_one 关联的对象

php - 使用 AJAX 动态地同时动态地创建多个动态表

javascript - AJAX 调用正在处理但未在 Rails View 中呈现

javascript - 连续的 ajax 调用卡住 chrome 和 IE

javascript - 重新启用 event.preventDefault();