开发者

jQuery: append a templated box with some inner html

开发者 https://www.devze.com 2022-12-11 16:55 出处:网络
Sorry if my title is not clear, I\'m not sure how to word this. I\'m n开发者_如何学运维ew to jQuery, and here is what I am trying to do.

Sorry if my title is not clear, I'm not sure how to word this. I'm n开发者_如何学运维ew to jQuery, and here is what I am trying to do.

I want to show one or more announcement boxes on top of the webpage.

Let's say I have some kind of template "div" element with a class name, some html to make it into a pretty box. And a placeholder or something, where the actual message (html) will be.

Then I would use $.append to insert each of this boxes on my page, specifying the custom message for that box.

My problem is, how can I create such a DIV template and how can I add content to it?

I hope this is clear ...


You could create a helper function like this:

$.messageDiv = function(message, style){
    var $div = $('<div>').addClass('message-div message-style-' + style);
    var $message = $('<p>').appendTo($div);

    $message.html(message); // Or use .text() if message contains no HTML or if should be escaped if it does contain HTML
    return $div;
}

And then use it to add the message to the page:

$('#content').prepend($.messageDiv('My Cool Message!', 'warning'));

And it would create and prepend (Added to the inside top of #content) this markup:

<div class="message-div message-style-warning">
    <p>Your text here</p>
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消