我对警报消息有疑问。正常显示,当用户按下x
(关闭)时我可以关闭它,但是当用户试图再次显示它时(例如,点击按钮事件)则不显示. (此外,如果我将此警报消息打印到控制台,它等于 []
。)我的代码在这里:
<div class="alert" style="display: none">
<a class="close" data-dismiss="alert">×</a>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
和事件:
$(".alert").show();
P.S! 我只需要在某些事件发生后(例如,单击按钮)显示警报消息。或者我做错了什么?
最佳答案
Data-dismiss 完全删除该元素。请改用 jQuery 的 .hide() 方法。
快速修复方法:
像这样使用内联 javascript 隐藏元素 onclick:
<div class="alert" style="display: none">
<a class="close" onclick="$('.alert').hide()">×</a>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
<a href="#" onclick="$('alert').show()">show</a>
然而,这应该只在您懒惰时使用(如果您想要一个可维护的应用程序,这不是一件好事)。
做对的方法:
创建用于隐藏元素的新数据属性。
Javascript:
$(function(){
$("[data-hide]").on("click", function(){
$("." + $(this).attr("data-hide")).hide()
// -or-, see below
// $(this).closest("." + $(this).attr("data-hide")).hide()
})
})
然后在标记中将 data-dismiss 更改为 data-hide。 Example at jsfiddle .
$("." + $(this).attr("data-hide")).hide()
这将隐藏所有具有 data-hide 中指定类的元素,即:data-hide="alert"
将隐藏所有具有 alert 类的元素。
Xeon06提供了替代解决方案:
$(this).closest("." + $(this).attr("data-hide")).hide()
这只会隐藏最近的父元素。如果您不想给每个警报一个唯一的类,这将非常有用。但是请注意,您需要将关闭按钮放在警报中。
.closest 的定义来自 jquery doc :
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
关于javascript - Twitter Bootstrap 警报消息关闭并再次打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550477/