Clearest way to build html elements in jQuery

前端 未结 10 1173
一个人的身影
一个人的身影 2020-12-12 11:12

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 als

相关标签:
10条回答
  • 2020-12-12 11:48

    2015 answer: for older browsers, use multiline.

    var str = multiline(function(){/*
    <!doctype html>
    <html>
        <body>
            <h1>❤ unicorns</h1>
        </body>
    </html>
    */});
    

    For ES6, use JavaScript template strings

    var str = `
    <!doctype html>
    <html>
        <body>
            <h1>❤ unicorns</h1>
        </body>
    </html>`
    
    0 讨论(0)
  • Here's an example that uses $(htmlString) and mimics the standard layout of HTML code:

    function getPage(title, contents) {
      return (
        $("<div>", {id: "container", class: "box"}).append(
          $("<div>", {class: "title"}).append(
            $("<h1>").text(title)
          ),
          $("<div>").html(contents)
        )
      );
    }
    
    0 讨论(0)
  • 2020-12-12 11:50

    I find the functional approach very convenient. For instance

    // reusable generics TABLE constructor helpers
    var TD = function(content) { return $('<td>', { html: content }) }
    var TH = function(content) { return $('<th>', { html: content }) }
    var TR = function(cell, cells) {  // note the kind of cell is a 2^order parameter
        return $('<tr>', { html: $.map(cells, cell) })
    }
    
    // application example
    THEAD = $('<thead>', {html:
        TR(TH, [1,2,3,4])})
    TBODY = $('<tbody>', {html: [
        TR(TD, ['a','b','c','d']),
        TR(TD, ['a','b','c','d']),
    ]})
    

    now the call

    $('#table').append($('<table>', {html: [THEAD, TBODY]}))
    

    yields

    <table><thead><tr><th>1</th><th>2</th><th>3</th><th>4</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td><td>d</td></tr><tr><td>a</td><td>b</td><td>c</td><td>d</td></tr></tbody></table>

    edit

    I have refined my approach, now available for instance as html_uty.js

    0 讨论(0)
  • 2020-12-12 11:55

    You could possibly look into javascript view templates:

    http://embeddedjs.com/

    http://jupiterjs.com/news/jquery-view-client-side-templates-for-jquery

    http://javascriptmvc.com/docs.html#!jQuery.View

    0 讨论(0)
  • 2020-12-12 11:58

    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.

    0 讨论(0)
  • 2020-12-12 12:02

    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.

    0 讨论(0)
提交回复
热议问题