【发布时间】:2019-08-02 15:10:34
【问题描述】:
如何显示和隐藏 Bootstrap 警报?
我尝试过使用$().alert("open"),但这似乎无法解决问题:
// Hide the alert when DOM loads:
$("#alert").alert("close");
// Show alert on given info click:
$("#info").click(function() {
console.log("Got clicked");
$("#alert").alert();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<label class="" for="">
Checkbox <span class="glyphicon glyphicon-info-sign" id="info"></span>
</label>
<div class="checkbox">
<label>
<input type="checkbox" id="" value="option1" aria-label="..."> Sample
</label>
</div>
</div>
<div class="alert alert-info alert-dismissible" role="alert" id="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Note: </strong> Test... and that is that. <a href="#" class="alert-link">More info</a>
</div>
</form>
引导provides 方法关闭警报,但不(重新)打开这些警报。我可以简单地选择使用$.show() 和$.hide(),但这是应该的方式吗?
我将无法再使用data-dismiss="alert":
//$("#alert").alert("close");
$("#alert").hide();
$("#info").click(function() {
console.log("Got clicked");
$("#alert").show();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<label class="" for="">
Checkbox <span class="glyphicon glyphicon-info-sign" id="info"></span>
</label>
<div class="checkbox">
<label>
<input type="checkbox" id="" value="option1" aria-label="..."> Sample
</label>
</div>
</div>
<div class="alert alert-info alert-dismissible" role="alert" id="alert">
<button type="button" class="close" onclick="$('#alert').hide();" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Note: </strong> Test... and that is that. <a href="#" class="alert-link">More info</a>
</div>
</form>
【问题讨论】:
-
我认为您混淆了 JQuery 和 Bootstrap。 Bootstrap 所做的只是为常规的
alerts 提供样式。 jQuery 提供$().show/hide。浏览器对象模型提供了window对象,alert()是一个方法。 -
但是
data-dismiss不是 JQuery 吗?这是 Bootstrap 用来运行 JQuery$().alert()功能的 HTML 属性? -
没有。该属性仅提供样式。 JavaScript 都是 JQery。
-
我认为最短的方法是简单地使用
onclick="$(....).toggle()"之类的东西。还要注意用小号c写onclick,一些(旧)浏览器会出现大小写错误的问题。 -
@Barrosy 您在 cmets 中的最后一个问题的答案是 yes。 Bootstrap 警报除了闪烁您的消息并从 DOM 中删除 (
.alert) 容器元素外,并没有做更多的事情。你可以用它做任何你想做的事(比如你的第二个示例代码块),我认为它无论如何都不会损害 DOM(当然,除非你做了一些疯狂的事情)
标签: javascript jquery html twitter-bootstrap-3