我有一个 Bootstrap 警报,如果其中没有文本,它应该隐藏。我能够让警报不占据整个屏幕,但剩下的是页面顶部的一小块。我一直在尝试我在这里找到的这段代码 ( How to hide Bootstrap alert box when no message ) 但这种情况发生了。
代码如下:
<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 %>
你可以动态地设置这个类,例如 alert
、notice
、success
、danger
,就像你的 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/