javascript - 如果没有内容,如何隐藏 Bootstrap 警报?

标签 javascript html ruby-on-rails twitter-bootstrap

我有一个 Bootstrap 警报,如果其中没有文本,它应该隐藏。我能够让警报不占据整个屏幕,但剩下的是页面顶部的一小块。我一直在尝试我在这里找到的这段代码 ( How to hide Bootstrap alert box when no message ) 但这种情况发生了。 enter image description here

代码如下:

<script type="text/javascript">
$(document).ready(function () {
    if (<%= notice %>.length != 0) {
    $("#notice span").text(<%= notice %>);
    $("#notice").show();
}
else {
    $("#notice").hide();
}
});
</script>

<div id="notice" style="text-align: center;">
<span role="alert" class="alert alert-success">
<%= notice %>
</span>
</div>

编辑:<% notice %> 是提示文字,#notice 是div的id

最佳答案

你可以在没有 jQuery 的情况下简单地做到这一点你不需要像下面这样的 jQuery

<% if notice.present? %>
  <div id="notice" style="text-align: center;">
    <span role="alert" class="alert alert-success">
        <%= notice %>
    </span>
  </div>
<% end %>

你可以动态地设置这个类,例如 alertnoticesuccessdanger,就像你的 Controller flash 是

flash[:alert] = 'Model was successfully created.'
or
flash[:notice] = 'Model was successfully created.'
or
flash[:success] = 'Model was successfully created.'
or
flash[:danger] = 'Model was successfully created.'

现在您的 Flash 部分将是

<% flash.each do |name, msg| %>
    <div id="notice" style="text-align: center;">
        <span role="alert" class="alert alert-<%="#{name}" %>">
        <p><%= msg if msg.is_a?(String) %></p>
    </span>
<% end %>

就是这样。

希望能帮到你。

关于javascript - 如果没有内容,如何隐藏 Bootstrap 警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48999919/

相关文章:

Mysql复制某些列

Javascript代码进入无限循环

javascript - Windows Phone 7 上的 window.open

html - 如何在移动设备上使用 css 使图像居中?

css - 溢出不够

ruby-on-rails - 删除 rails 中的多个项目的 Restful 方法是什么?

ruby-on-rails - Rails 正则表达式电子邮件验证,不允许使用空格

javascript - 对 URL 的异步调用

javascript - React JS View 事件

javascript - 在 mongodb 中使用外部引用进行聚合