我编写了一个简单的JQuery脚本,可以在不同时间段自动关闭我网页上的每个警报。
这是我的JQuery代码:
<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>
以下是我的两个示例警报:
ondrop
每个警报都有一个带值的自定义属性,用作警报关闭时间段。
出于某种原因警报关闭无效。
答案 0 :(得分:1)
$(this)
范围内更改了 setTimeout
。将其缓存在变量中。在我的例子中that
。
$(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>
答案 1 :(得分:0)
我会在父元素上使用 .on("DOMSubtreeModified")
:
<div id="messages"></div>
<script>
// If anything gets appended in #messages, timer is set to remove first element
$("#messages").on('DOMSubtreeModified', function(){
var firstChild = this.firstChild;
setTimeout(function(){
$(firstChild).alert("close"); //You are looking for this
}, 2000);
})
</script>