我编写了一个简单的 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">×</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">×</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">×</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">×</span>
</button>
alert two
</div>
关于javascript - Bootstrap 警报自动关闭不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837562/