问题
How should I go about adding a new alert box dynamically to a page with foundation? It looks like I would have to insert the html markup for the box and then reinitialize foundation for the whole page... that can't be right, can it?
Is there some easy method for adding an alert box dynamically?
I would expect an api such as: $("#myElement").foundation('alert', "foo 123");
Example:
$.post("/some/url", {some:'data'})
.fail(function(){
$("#myElement").foundation('alert', 'Process failed!');
});
回答1:
No API but you can do something like this:
$.post("/some/url", {some:'data'})
.fail(function(){
var alertBox = '<div data-alert class="alert-box"> Sorry, the request failed. <a href="#" class="close">×</a></div>';
$("#errorArea").append(alertBox).foundation();
});
回答2:
I found a slightly better way to do this, similar to what the @Ben Polinsky did. The only difference is that it only re-initializes the "alert" module instead of everything.
// Create the HTML
var $message = $('<div data-alert class="alert-box"><span></span><a href="#" class="close">×</a></div>');
// Fill it
$message.addClass(severity).children("span").text(message);
// Add the div and re-initialize foundation-alert for its parent
$("#errorArea").prepend($message).foundation(
"alert", // libraries -- if it's undefined or "reflow" it will loop on all libs
undefined, // method -- if it's undefined it will call init
{speed: "slow", animation: "slideUp", callback: function() {}} // options -- optional, to customize the alert box
);
回答3:
jadkik94 has given a very nice example. Based on it I have a more complete/understandable solution:
var message = "You are doomed";
var type = "alert"
showMessage(message, type);
function showMessage(message, type) {
var alertMarkup = $('<div data-alert class="alert-box"><span></span><a href="#" class="close">×</a></div>');
alertMarkup.addClass(type);
alertMarkup.children("span").text(message);
$("#foundation-alerts").prepend(alertMarkup).foundation(
"alert",
undefined
);
}
来源:https://stackoverflow.com/questions/21681416/dynamic-alert-box-with-foundation