简体   繁体   中英

How do I add 'x' number of <td> elements into a <tr> element in a for loop? [jQuery]

I am trying to make a square table dynamically through jQuery

My code so far is

$(document).ready(function() {
  $('body').append('<table></table>');
  initial();
});

var input = 16

function initial () {
  for (i = 0; i < input; i++) {
    $('table').append('<tr></tr>');
    $('tr').append('<td></td>');
  }
}

What I am trying to do is if I add 16 table row elements, then 16 table data elements will be added to each one, effectively creating a 16x16 grid

My current code only creates half of the table I have to do this through jQuery

Sorry if it's simple, but I'm a bit daft

Thanks

You have to make two loops one after another:

$(document).ready(function() {
  $('body').append('<table></table>');
  initial();
});

var input = 16

function initial () {
  for (i = 0; i < input; i++) {
    $('table').append('<tr></tr>');
  }
  for (j = 0; j < input; j++) {
    $('tr').append('<td>content</td>');    
  }
}

Btw its wrong way to create table, because you every time referring to DOM, which is expensive. You should first create string with table, then append it once to DOM:

var input = 16
function initial () {
  var output = "<table>"
  for (i = 0; i < input; i++) {
    output += "<tr>";
    for (j = 0; j < input; j++) {
      output += "<td>content</td>";
    }
    output += "</tr>";
  }
  output += "</table>"
  $('body').append(output);
}

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