【问题标题】:bootstrap alert dismiss on click引导警报在单击时关闭
【发布时间】:2015-06-05 21:39:45
【问题描述】:

我已经尝试了在这里和谷歌上可以找到的所有代码,但似乎没有任何效果。我试图让我的警报在鼠标点击页面上的任意位置时被解除。 我的 application.js 中有//=require bootstrap,它在列表中是最后一个。以下代码是我希望被忽略的。

<% flash.each do |key, value| %>
 <div class="col-md-4 col-md-offset-4">
  <div class="alert alertPrimary alert-dismissible fade in textCenter">
  <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
   <% if value.is_a?(String) %>
     <%= value %>
   <% else %>
   <% end %>
  </div>
 </div>
<% end %>

return '' if resource.errors.empty?

messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
html = <<-HTML
<div class="alert alert-danger alert-dismissible fade in textCenter">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
  #{messages}
</div>
HTML

html.html_safe

我似乎找不到任何可以解决问题的 javascript/jquery。当我在按钮代码中添加“x”时,它会在您单击它时关闭警报,但这不是我正在寻找的行为。我只希望当用户点击任何地方时警报消失。

我的整个application.js 文件

//= require turbolinks
//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require bootstrap
//= require_tree .

【问题讨论】:

    标签: javascript jquery twitter-bootstrap ruby-on-rails-4


    【解决方案1】:

    你可以这样使用:

    // Use JQuery selector and bind a function to the click event
    // $("body") selects the <body> tag
    $("body").click(function(){  
        $(".alert").alert("close");
    });
    

    此方法可通过bootstrap's alert plugin 获得,它是bootstrap.js 的一部分

    示例:

    $(document).ready(function() {
      $(".content").click(function() {
        $(".alert").alert("close");
      });
    });
    .content {
      width: 100%;
      height: 400px;
      background: #aaa;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
    <div class="content">
      <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
        </button>
        <strong>Warning!</strong> Better check yourself, you're not looking too good.
      </div>
    </div>

    【讨论】:

    • 您是否包含了 bootstrap.js 文件? maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js我不确定bootstrap是否加载JQuery,如果没有你也应该添加它
    • 如果你还没有设置正确的选择器而不是.body
    • 用我的整个application.js 文件更新了我的帖子。为什么.body 选择错误?这不是我需要的吗?我将上面的代码解释为“一旦页面完成加载,请监听点击,如果 html 正文上有点击,则关闭所有警报类”
    • 在我的示例中不,我使用了 .body 类,但现在我注意到它可能令人困惑,我将立即更改它
    • 抱歉,我应该听懂了。我只是在学习。我知道. 表示类,# 表示 id。我的错。
    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多