javascript - Bootstrap 警报自动关闭不起作用

标签 javascript jquery twitter-bootstrap

我编写了一个简单的 JQuery 脚本来在不同时间段自动关闭网页上的每个警报。

这是我的 JQuery 代码:

$(function() {
        var alert = $('div.alert[auto-close]');
        alert.each(function() {
            var time_period = $(this).attr('auto-close'); 
            setTimeout(function() {
                $(this).alert('close');
            }, time_period);
        });
     });

这是我的两个示例警报:

<div class="alert alert-danger alert-dismissible" role="alert" auto-close="3000">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                alert one
            </div>
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                alert two
            </div>

每个警报都有一个带有值的自定义属性,用作警报关闭时间段。

由于某种原因,警报关闭不起作用。

最佳答案

$(this)setTimeout 范围内更改。将其缓存在变量中。 在我的示例中

$(function() {
  var alert = $('div.alert[auto-close]');
  alert.each(function() {
    var that = $(this);
    var time_period = that.attr('auto-close');
    setTimeout(function() {
      that.alert('close');
    }, time_period);
  });
});

工作片段:

$(function() {
  var alert = $('div.alert[auto-close]');
  alert.each(function() {
    var that = $(this);
    var time_period = that.attr('auto-close');
    setTimeout(function() {
      that.alert('close');
    }, time_period);
  });
});
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="moo" class="alert alert-danger alert-dismissible" role="alert" auto-close="3000">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
  </button>
  alert one
</div>
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
  </button>
  alert two
</div>

关于javascript - Bootstrap 警报自动关闭不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837562/

相关文章:

javascript - 在maven Spark java应用程序中运行html文件

javascript - 标题大写一句话——哪种解决方案更好,为什么?

javascript - 基本动画效果——我应该使用 jQuery 还是 HTML5 Canvas?

jquery - 如何在乘法和除法中保持小数精度(在 jQuery、javascript 中)?

javascript - 单击链接时不显示表单

javascript - html5 canvas javascript 复制图片

javascript - Meteor 应用程序访问其根目录之外的文件

javascript - 如何根据 AngularJS 输入类 $invalid 将 Twitter Bootstrap 类设置为错误?

html - Bootstrap 垂直时间轴到水平时间轴

javascript - Angular Directive(指令)中的下拉子菜单和递归