As jQuery devs know, jQuery allo开发者_Python百科ws easy dynamic HTML creation like this
var d = $('<div/>')
.append('some text')
.append(
$('<ul/>').append(
$('<li/>').text('list item')
.css("color", "blue")
.click(function() {
// do something
})
)
);
What's a good coding convention for creating dynamic HTML like this that can go down an arbitrary number of levels, while still being able to identify where I am in the element hierarchy and can spot if I've closed all the parentheses/braces properly?
Please don't direct me to a templating library.
Don't forget you can pass a map of properties as the second argument when creating a new element (jQuery 1.4 +):
$("<li/>", {
text: "list item",
css: { color: "blue" },
click: function(){
// do something
}
)
See http://api.jquery.com/jQuery/#creating-new-elements
Use templates like Handlebars or EJS to decouple templates from the behavior specific code. Handlebars have an extra added feature, that is to precompile the template and convert it in a minified js. This minified js actually reduces the http calls and loads the page faster.
While in the template, you can add classes or ids to give styling mentioned in common css files.
精彩评论