How do I force jQuery append to NOT automatically close a tag?

前端 未结 3 1371
借酒劲吻你
借酒劲吻你 2020-11-30 11:07

I have a JavaScript object with about 1000 properties and want to create a

of these entries, with eight properties in a single row,
相关标签:
3条回答
  • 2020-11-30 11:26

    You're thinking in terms of html markup, with using append you should be thinking in terms of html DOM, you don't have open tags and close tag just elements.

    You can use a string to build your html then append it to the table

    var ctr = 0;
    var innerTable = '<tr>';
    
    for (var g in g2u) {
      innerTable += '<td><span class="rom">'+g+'</span>\n';
      innerTable += '<span class="eh">'+g2u[g]+'</span>\n';
      innerTable += '<span class="rom">&nbsp;&nbsp;</span></td>\n';
      ctr++;
      if (ctr % 8 == 0) {
        innerTable += '</tr><tr>\n';
      }
    }
    $("#list").append(innerTable);
    
    0 讨论(0)
  • 2020-11-30 11:30

    If you append it will obviously try to close tags. Try to put your html in an string than append that string to the dom.

        <script>
        var ctr = 0;
        var html='<tr>';
    
        for (var g in g2u) {
          html+='<td><span class="rom">'+g+'</span>\n';
          html+='<span class="eh">'+g2u[g]+'</span>\n';
          html+='<span class="rom">&nbsp;&nbsp;</span></td>\n';
          ctr++;
          if (ctr % 8 == 0) {
            html+='</tr><tr>\n';
          }
        }
    
    
         $("#list").append(html);
    
    0 讨论(0)
  • 2020-11-30 11:31

    Seven years, but I tought I could help anyone else that comes across a similar problem. For example, if you want to use JQuery's $.each() with .append() to make an list of users, such as:

    <ul>
      <li>User 1</li>
      <li>User 2</li>
    </ul>
    

    Here's what you DON'T want to do:

    element.append(`<ul>`);
    $.each(users, function(key, value) {
      element.append(`<li>${value.name}</li>`);
    });
    element.append(`</ul>`);
    

    The output will be something like:

    <ul></ul>
    <li>User 1</li>
    <li>User 2</li>
    

    Instead, here's what you WANT to do:

    element.append(`<ul id="ul-users"></ul>`);
    $.each(users, function(key, value) {
      $("#ul-users").append(`<li>${value.name}</li>`);
    });
    

    So the output will be as follows:

    <ul id="ul-users">
      <li>User 1</li>
      <li>User 2</li>
    </ul>
    
    0 讨论(0)
提交回复
热议问题