Dopo aver esaminato alcune delle risposte qui e in un altro thread, ecco cosa sono finito con:
Ho creato una funzione denominata showAlert()che aggiungerebbe dinamicamente un avviso, con un'opzione typee closeDealy. In modo che tu possa, ad esempio, aggiungere un avviso di tipo danger(cioè, avviso di pericolo di Bootstrap) che si chiuderà automaticamente dopo 5 secondi in questo modo:
showAlert("Warning message", "danger", 5000);
Per ottenere ciò, aggiungi la seguente funzione Javascript:
function showAlert(message, type, closeDelay) {
if ($("#alerts-container").length == 0) {
// alerts-container does not exist, add it
$("body")
.append( $('<div id="alerts-container" style="position: fixed;
width: 50%; left: 25%; top: 10%;">') );
}
// default to alert-info; other options include success, warning, danger
type = type || "info";
// create the alert div
var alert = $('<div class="alert alert-' + type + ' fade in">')
.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
$("#alerts-container").prepend(alert);
// if closeDelay was passed - set a timeout to close the alert
if (closeDelay)
window.setTimeout(function() { alert.alert("close") }, closeDelay);
}