Jquery append - Opening and closing a tag

前端 未结 3 1567
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 09:51

I have a jquery block like this. After the html is rendered i see that the

tag opens and closes immediately, same way,
相关标签:
3条回答
  • 2020-12-21 10:36

    Instead of appending each line you could store it in a variable like below, and append it all together:

    content = '';
    
    content += '<article class="preview">';
    content += '<div class="bar">';
    content += '<span class="left"><small>'+value.dTime+'</small></span>';
    

    And so on.

    And then append content in the end. Just put it into your function.

    0 讨论(0)
  • 2020-12-21 10:38

    If you want that all elements are in the article tag, you should write:

    .append(
       $( '<article class="preview"> )
       .append( ... )
    )
    
    0 讨论(0)
  • 2020-12-21 10:40

    Jquery's append function takes a DOM node, HTML string, or javascript object as input. So when you call your first append, there is no closing tag for the article, so it builds it into a complete DOM node by adding the closing tag for you. Then, when you go to append your next item, it actually appends completely after the previous DOM node (after the closing tag).

    Instead, I recommend you build the HTML string first, then append it all at once.

    For example, you should do the following:

    var html = "<article class='preview'><div class='bar'><span class='left'><small>........";
    $("#newlist").append(html);
    

    Of course, there are better ways of doing this, such as using a templating engine such as Mustache.JS, but this should at least get it working for you.

    Hope this helps

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