jQuery - Best Practice for creating complex HTML Fragments

后端 未结 9 1468
情深已故
情深已故 2021-01-30 03:21

Is there a general best practice for creating somewhat complex HTML elements in jQuery? I\'ve tried a few different ways.

First I tried using createElement and chaining

相关标签:
9条回答
  • 2021-01-30 03:52

    Since HTML5 there's the <template> tag.

    $(function () {
        // Get template
        var template = $("#template").html();
    
        // Create a new row from the template
        var $row = $(template);
    
        // Add data to the row
        $row.find("td[data-template='firstName']").text("Foo");
        $row.find("td[data-template='lastName']").text("Bar");
    
        // Add the row to the table
        $("#table").append($row);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <template id="template">
      <tr>
        <td data-template="firstName"></td>
        <td data-template="lastName"></td>
      </tr>
    </template>
    
    <table id="table">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
      </tr>
    </table>

    0 讨论(0)
  • 2021-01-30 03:54

    You don't have to call document.createElement:

    $('#existingContainer').append(
      $('<div/>')
        .attr("id", "newDiv1")
        .addClass("newDiv purple bloated")
        .append("<span/>")
          .text("hello world")
    );
    

    There are all sorts of useful tools in jQuery for extending/ammending the DOM. Look at the various "wrap" methods for example.

    Another possibility: for really big blobs of new content, you may be better off having your server prepare those (using the server-side templating system, whatever that is for you) and fetching those with $.load() or some other ajax approach.

    0 讨论(0)
  • 2021-01-30 03:55

    I like the templating language Handlebars.js

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