我见过很多在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.

推荐答案

Templates are great and if you have access to them in your project, I suggest you use them. If you're using Underscore or Lodash it's built in. In some cases however, you will need to build HTML in your code whether it's refactoring or testing. I've found that the below format is the clearest to read when that is the requirement.

Note: The HTML spec allows single OR double quotes for attributes in your markup so don't bother with all the crazy escaping.

this.$fixture = $([
  "<div>",
  "  <div class='js-alert-box'></div>",
  "  <form id='my-form-to-validate'>",
  "    <input id='login-username' name='login-username'>",
  "  </form>",
  "</div>"
].join("\n"));

Jquery相关问答推荐

在函数 jQuery 中更改语言

如何在jQuery中判断粘贴剪贴板中字母输入的增加/减少

与其他 Javascript 框架相比,为什么 jQuery 被如此广泛地采用?

jquery克隆div并将其附加在特定div之后

[本机代码]是什么意思?

jQuery $(document).ready () 触发两次

如何使用 jQuery 将表格的一行滚动到视图 (element.scrollintoView) 中?

JSLint 消息:未使用的变量

为特定请求禁用 ajaxStart() 和 ajaxStop()

Jquery,清除/清空 tbody 元素的所有内容?

Bootstrap 3.0 弹出框和工具提示

PHPStorm IDE 中低效的 jQuery 使用警告

页面加载后如何执行jquery代码?

如何使用 JQuery $.scrollTo() 函数滚动窗口

更改 div 的内容 - jQuery

JavaScript 中的简单节流阀

jquery $(window).width() 和 $(window).height() 在未调整视口大小时返回不同的值

如何使用 JQuery 删除onclick?

jquery ui Dialog:无法在初始化之前调用对话框上的方法

清除表jquery