Clearest way to build html elements in jQuery

2019-01-29 20:48发布

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.

9条回答
爷、活的狠高调
3楼-- · 2019-01-29 21:43

My advice : don't try to build html elements with jQuery, it's not its responsability.

Use a Javascript templating system like Mustache or HandlebarJs.

With a very limited number of line, you can create your html elements directly from a Javascript object. It's not complicated, only 2 functions and a template.

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

var context  = {title: "My New Post", body: "This is my first post!"}
var template = Handlebars.compile($("#template-skeleton"));
var html     = template(context);

Edit:
Another example without html, pure Javascript (from ICanHaz) :

var skeleton = '<div><h1>{{title}}</h1><div class="content">{{content}}</div></div>';
var data = { title: "Some title", content: "Some content" };
var html = Mustache.to_html(skeleton, data);

It is much more maintainable than a series of concatenation.

查看更多
老娘就宠你
4楼-- · 2019-01-29 21:45

When it comes to DOM building I try to avoid string concatenations as they might lead to subtle bugs and non properly encoded output.

I like this one:

$('<div/>', {
    html: $('<h1/>', {
        html: title
    }).after(
        $('<div/>', {
            'text': content,
            'class': 'content'
        })
    )
}).appendTo('body');

generates:

    ...
    <div><h1>some title</h1><div class="content">some content</div></div>
</body>

and it ensures proper HTML encoding and DOM tree building with matching opening and closing tags.

查看更多
登录 后发表回答