最清晰的方式来在jQuery中构建html元素 [英] Clearest way to build html elements in jQuery

查看:118
本文介绍了最清晰的方式来在jQuery中构建html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多不同的样式(和几种不同的方法)在jQuery中创建元素。我很好奇的是最清楚的方式来构建它们,以及任何特定的方法客观上比另一个更好的任何原因。下面是我看到的样式和方法的一些例子

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.

推荐答案

模板是伟大的,如果你有你的项目中访问他们,我建议你使用它们。如果您使用下划线 Lodash 它是内置的。但在某些情况下,您将需要在代码中构建HTML,无论是重构还是测试。我发现下面的格式是最清楚的,当这是要求。

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.

注意: HTML规范允许单引号或双引号的属性在你的标记,所以不要打扰所有的疯狂转义。

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中构建html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆