Javascript 动态创建 Bootstrap CSS 警报消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8965018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically creating Bootstrap CSS alert messages
提问by tibbe
I'm trying to dynamically create alert messages using the jQuery plugin for Bootstrap CSS. I want to create and destroy alerts on certain events (e.g. AJAX success/error). Here's a non-working snippet of my code:
我正在尝试使用 Bootstrap CSS 的 jQuery 插件动态创建警报消息。我想创建和销毁某些事件(例如 AJAX 成功/错误)的警报。这是我的代码的非工作片段:
var alertVisible = false;
function fetchData() {
function onDataReceived(stats) {
if (alertVisible) {
$(".alert-message").alert("close");
}
alertVisible = false;
// Do stuff with data...
}
function onError() {
$(".alert-message").alert();
alertVisible = true;
}
$.ajax({
dataType: 'json',
success: onDataReceived,
error: onError,
cache: false
});
};
and here's the corresponding HTML:
这是相应的 HTML:
<div class="row">
<div class="alert-message error fade in hide span16" data-alert="alert">
<a class="close" href="#">×</a>
<p>Lost connection to server.</p>
</div>
</div>
My first problem is that the alert is showed by default. I can kinda solve this by using the hide
class. However, if you close an alert (by clicking on the close button) then creating new asserts no longer works (I guess the DOM element is gone). How are you supposed to use Bootstrap alerts?
我的第一个问题是警报默认显示。我可以通过使用hide
类来解决这个问题。但是,如果您关闭警报(通过单击关闭按钮),则创建新断言不再有效(我猜 DOM 元素已经消失)。你应该如何使用 Bootstrap 警报?
回答by Sanjay
This answer refers to Bootstrap 2.
这个答案是指 Bootstrap 2。
When an alert is closed, it is removed from the DOM.
当警报关闭时,它会从 DOM 中删除。
If you want to an alert to reappear later, make sure to notput data-dismiss="alert"
in the close button as follows:
如果您想稍后再次出现警报,请确保不要data-dismiss="alert"
按如下方式放置关闭按钮:
<div class="alert fade in" id="login-error" style="display:none;">
<button type="button" class="close">×</button>
Your error message goes here...
</div>
Then, bind the close button to simply hide the alert when it's pressed:
然后,绑定关闭按钮以在按下时隐藏警报:
$('.alert .close').on('click', function(e) {
$(this).parent().hide();
});
When you want the tooltip to reappear, simply show it.
当您希望工具提示重新出现时,只需显示它即可。
$('#login-error').show();
回答by Eamonn O'Brien-Strain
You could just dynamically add the DOM elements for the alert.
您可以为警报动态添加 DOM 元素。
Javascript:
Javascript:
function addAlert(message) {
$('#alerts').append(
'<div class="alert">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + message + '</div>');
}
function onError() {
addAlert('Lost connection to server.');
}
HTML:
HTML:
<div id="alerts"></div>
In the case of multiple alerts, this version will result in multiple alerts piling up that must be individually dismissed by the end user. Depending on how many alerts you expect and how important it is for the user to see each one you might want to modify this to delete old alerts.
在多个警报的情况下,此版本将导致多个警报堆积,最终用户必须单独关闭这些警报。根据您期望的警报数量以及用户查看每个警报的重要性,您可能希望修改此设置以删除旧警报。
Also, with a little refactoring you can extend this to create warning, info, and success alerts in addition to this error alert.
此外,通过一些重构,除了此错误警报之外,您还可以扩展它以创建警告、信息和成功警报。
回答by Игорь К.
Best way that i know:
我知道的最好方法:
HTML:
HTML:
<div class="alert alert-block alert-error fade in" id="cert-error" style="display:none;">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4 class="alert-heading">Этот файл не подходит!</h4>
<p>Недопустимый тип файла! Выберите файл вида: *.cer, *.crt</p>
<p>
<a class="btn btn-danger" href="#">Take this action</a> <a class="btn" href="#">Or do this</a>
</p>
</div>
JS:
JS:
$('.alert .close').live("click", function(e) {
$(this).parent().hide();
});
function showAlert() {
$(".alert").addClass("in");
$("#cert-error").show();
}
function closeAlert() {
$("#cert-error").hide();
}
Now we can display notifications using showAlert() and hide them with closeAlert().
现在我们可以使用 showAlert() 显示通知并使用 closeAlert() 隐藏它们。
回答by isapir
I took Eamonn's answer and improved on it a bit, adding an optional type
and closeDelay
, so that you can, for example, add an alert of type danger
that will close automatically after 5 seconds like so:
我接受了 Eamonn 的回答并对其进行了一些改进,添加了一个可选的type
and closeDelay
,以便您可以添加一个类型的警报,该警报danger
将在 5 秒后自动关闭,如下所示:
showAlert("Warning message", "danger", 5000);
To achieve that, add the following JavaScript function:
为此,请添加以下 JavaScript 函数:
function showAlert(message, type, closeDelay) {
var $cont = $("#alerts-container");
if ($cont.length == 0) {
// alerts-container does not exist, create it
$cont = $('<div id="alerts-container">')
.css({
position: "fixed"
,width: "50%"
,left: "25%"
,top: "10%"
})
.appendTo($("body"));
}
// default to alert-info; other options include success, warning, danger
type = type || "info";
// create the alert div
var alert = $('<div>')
.addClass("fade in show alert alert-" + type)
.append(
$('<button type="button" class="close" data-dismiss="alert">')
.append("×")
)
.append(message);
// add the alert div to top of alerts-container, use append() to add to bottom
$cont.prepend(alert);
// if closeDelay was passed - set a timeout to close the alert
if (closeDelay)
window.setTimeout(function() { alert.alert("close") }, closeDelay);
}
回答by Steven Woolston
You could consider an implementation of the Toastr library (https://github.com/CodeSeven/toastrby John Papa). Toastr gives you the alert functionality you require with native DOM event triggers or you can display a notification on PageLoad. It's worth investigating.
您可以考虑实现 Toastr 库(https://github.com/CodeSeven/toastrby John Papa)。Toastr 为您提供了本地 DOM 事件触发器所需的警报功能,或者您可以在 PageLoad 上显示通知。值得研究。
回答by Anuja Deshpande Patil
I think you are correct. On 'close' event of the alert whole Dom elements gets destroyed on which we have click. so we can not check the visibility property for that ids.
我认为你是对的。在警报的“关闭”事件中,我们单击的整个 Dom 元素都会被销毁。所以我们无法检查该 ID 的可见性属性。
So my suggestion is 'do not use 'close' class or close event of the bootstrap-alerts.js. Just get there classes for look and try to use traditional hide-show or some jquery tricks to get our task works.
所以我的建议是'不要使用'close'类或bootstrap-alerts.js的关闭事件。只需在那里寻找类并尝试使用传统的隐藏显示或一些 jquery 技巧来完成我们的任务。
回答by Joao Leme
Change removeElement() function. Line 59 from bootstrap-alert.js:
更改 removeElement() 函数。bootstrap-alert.js 第 59 行:
Change:
改变:
.remove()
To:
到:
.hide().css('opacity', 1);