jQuery - Best Practice for creating complex HTML Fragments

后端 未结 9 1470
情深已故
情深已故 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:54

    You don't have to call document.createElement:

    $('#existingContainer').append(
      $('
    ') .attr("id", "newDiv1") .addClass("newDiv purple bloated") .append("") .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.

提交回复
热议问题