我见过很多在jQuery中创建元素的不同风格(很少有不同的方法).我对建造它们的clearest种方法很好奇,也很好奇是否有一种特定的方法客观上比另一种方法更好,无论出于什么原因.下面是我看到的examples种样式和方法.
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.