I've seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and also if any particular method is objectively better than another for any reason. Below are some examples of the styles and methods that I've seen.
var title = "Title";
var content = "Lorem ipsum";
// escaping endlines for a multi-line string
// (aligning the slashes is marginally prettier but can add a lot of whitespace)
var $element1 = $("
<div><h1>" + title + "</h1>
<div class='content'>
" + content + "
</div>
</div>
");
// all in one
// obviously deficient
var $element2 = $("<div><h1>" + title + "</h1><div class='content'>" + content + "</div></div>");
// broken on concatenation
var $element3 = $("<div><h1>" +
title +
"</h1><div class='content'>" +
content +
"</div></div>");
// constructed piecewise
// (I've seen this with nested function calls instead of temp variables)
var $element4 = $("<div></div>");
var $title = $("<h1></h1>").html(title);
var $content = $("<div class='content'></div>").html(content);
$element4.append($title, $content);
$("body").append($element1, $element2, $element3, $element4);
Please feel free to demonstrate any other methods/styles you might use.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…