【发布时间】:2012-04-03 08:34:41
【问题描述】:
我已经看到在 jQuery 中创建元素的许多不同风格(以及几种不同的方法)。我很好奇构建它们的最清晰方法,以及任何特定方法是否出于任何原因客观上优于另一种方法。下面是我见过的一些样式和方法的示例。
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);
请随意演示您可能使用的任何其他方法/样式。
【问题讨论】:
-
前三个例子中,为什么要用jquery?在 jquery 选择器中编写完整的 html 只是性能损失。
var element2 = "<div><h1>"+title+"</h1>...</div>"; -
我也在用 jQuery 操作这些元素,所以如果我不使用 jQuery 创建它们,我无论如何都必须使用 jQuery 选择器。
标签: javascript jquery coding-style element