簡體   English   中英

如果沒有內容,如何隱藏引導程序警報?

[英]How to hide bootstrap alert if it has no content?

我有一個引導程序警報,如果里面沒有文字,它應該隱藏。 我能夠使警報不占據整個屏幕,但剩下的是頁面頂部的一小部分。 我一直在嘗試我在這里找到的這段代碼( 如何在沒有消息時隱藏 Bootstrap 警報框)但是發生了這種情況。 在此處輸入圖片說明

這是代碼:

<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就像您的控制器閃光一樣

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 %>

就是這樣。

希望能幫到你。

嘗試,

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

您不需要從 javascript 設置值, <%= notice %>會將其打印到視圖中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM