简体   繁体   中英

Creating html table from multidimensional javascript array

I was trying to create an html table from a nested for loop array in Javascript. When I try to append the <tr> tags to the table they get put in an element called tbody. How can I get the tr tags to be appended in the to the table element rather than the tbody element?

<html>
   <head>
        <script src='jq.js'></script>
   </head>
   <body>
       <table id='tb'></table>

   </body>
   <script>
       $('#tb').ready(     
        function() {
           console.log('table loaded');

          var ar = Array(2);

           for(var i=0;i<ar.length;i++){
              ar[i]=Array(2);
           }

           ar[0][0]='1';
           ar[1][0]='2';
           ar[0][1]='3';
           ar[1][1]='4';

           console.log('multidimensional array created!');

          for(var j=0;j<ar.length;j++){
              console.log('<tr>');
              $('#tb').append('<tr>');
              for(var k=0;k<2;k++){
                console.log('<td>'+ar[k][j]+'</td>');
                $('#tb').append('<td>'+ar[k][j]+'</td>');
              }
              console.log('</tr>');
              $('#tb').append('</tr>');
          }
          //expected:
          //12
          //34
          //actual
          //1 2 3 4
        });   
   </script>
</html>

Here's a jsfiddle

You can't. HTML tables are composed of three sections:

  • thead contains the header rows
  • tbody contains the data rows. You can have multiple of these if you want to make different groups of rows (eg if rows = months, you could have a separate tbody for each year).
  • tfoot contains the footer rows

If you put rows directly within the table tag, they're assumed to be part of tbody , and the browser creates this element automatically for you. You either have to put all your rows in tbody elements, or put them all directly within table .

The problem with your code has nothing to do with the tbody element. The problem is that you're trying to append td elements directly to the table, rather than to the tr elements. You're treating $('#tb').append() as if it's concatenating HTML text to the document, not inserting entire HTML elements. It should be something like:

     for(var j=0;j<ar.length;j++){
          console.log('<tr>');
          var row = $('<tr/>').appendTo('#tb');
          for(var k=0;k<2;k++){
            console.log('<td>'+ar[k][j]+'</td>');
            row.append('<td>'+ar[k][j]+'</td>'); // Append TD to TR
          }
      }

Or you can use CtrlX's answer, where he composes the entire table as a string, then inserts it into the DOM in one step. This is more efficient than building up the table incrementally.

You shouldn't append content like this to your table, because the browser must redraw the whole DOM, so it's not very efficient.

You should build your table inside a string, then append the whole string to your table, like this :

$('#tb').ready(     
    function() {
       console.log('table loaded');

      var ar = Array(2);

       for(var i=0;i<ar.length;i++){
          ar[i]=Array(2);
       }

       ar[0][0]='1';
       ar[1][0]='2';
       ar[0][1]='3';
       ar[1][1]='4';

       console.log('multidimensional array created!');
        //Prepare the outputed string
       var theTable = "";
      for(var j=0;j<ar.length;j++){
          theTable += '<tr>';
          for(var k=0;k<2;k++){             
            theTable += '<td>'+ar[k][j]+'</td>';
          }
          theTable += '</tr>';
      }
       //Finally appended the whole string to the table
       $('#tb').append(theTable);
      //expected:
      //12
      //34
      //actual
      //1 2 3 4
    });   

I've made a Jsfiddle for you : JSFiddle

Have fun !

   <body>
       <table id='tb1'>
           <tbody id='tb'>
           </tbody>

       </table>

   </body>
   <script>
       $('#tb').ready(     
        function() {
           console.log('table loaded');

          var ar = Array(2);

           for(var i=0;i<ar.length;i++){
              ar[i]=Array(2);
           }

           ar[0][0]='1';
           ar[1][0]='2';
           ar[0][1]='3';
           ar[1][1]='4';

           console.log('multidimensional array created!');

          for(var j=0;j<ar.length;j++){

              $('#tb').append('<tr>');
              for(var k=0;k<2;k++){                
                $('#tb').append('<td>'+ar[k][j]+'</td>');
              }             
              $('#tb').append('</tr>');
          }
          //expected:
          //12
          //34
          //actual
          //1 2 3 4
        });   
   </script>
</html>

this is the working code, on this fiddle http://jsfiddle.net/fn4Wz/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM