Appending content with jquery
Say we are attaching an error notification html/css pane/div to display some application layer errors returned from an ajax call out to server code. We branch on the presence of errors in the json response payload from the server and do the following:
$('#message').remove();
$('body').append('<div id="message" style="display: none;"><a href="" id="message-close">Close</a></div>');
$('#message-close').before(data['message'] + '开发者_如何学编程<ul id="errors"><li>' + data['errors'].join('</li><li>') + '</li></ul>');
$('#message').addClass('error').fadeIn();
This works just fine, but I would appreciate if people could point out improvements (basic or to make more elegant) or flaws on the jquery side that I might have missed. For instance, interspersing html fragments with jquery could be considered regrettable. By the way there is a click handler for #message-close defined elsewhere (as well as a success branch) as this is a redacted example. If this question belongs on the code review site instead of stackoverflow, please let me know. I haven't used the former, but am aware it exists.
This solution is definitely not more concise, but I think a programmatic approach scales as little bit better and is better suited for handling exceptions and corner cases (when they inevitably show up).
It also seems to read more straight forward than your example using append
then before
and so forth. This builds from the bottom up and nests data and event handlers as necessary.
$(function() {
// simulate ajax call
setTimeout(function() {
// ajax datas
var data = {errors: ['one', 'two', 'three']};
// close handler
var closeMessage = function() {
$(this).parents("div").fadeOut();
return false;
};
// render dialog
$('<div id="message" style="display: none;"></div>').append(
$('<ul id="errors"/>').append(
$.map(data.errors, function(t) {
return $("<li/>").text("an error: "+t)[0];
})))
.append(
$('<a href="#close" id="message-close">Close</a>')
.click(closeMessage))
.appendTo("body")
.fadeIn();
}, 1000);
});
See it working here on jsFiddle
精彩评论