简体   繁体   English

如何添加 <td> 元素成一个 <tr> for循环中的元素? [jQuery]

[英]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 我正在尝试通过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 我想做的是,如果我添加16个表行元素,那么每个表将添加16个表数据元素,从而有效地创建了16x16的网格

My current code only creates half of the table I have to do this through jQuery 我当前的代码仅创建表的一半,我必须通过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. 顺便说一句创建表的错误方法,因为您每次都引用DOM,这很昂贵。 You should first create string with table, then append it once to DOM: 您应该首先使用表创建字符串,然后将其附加到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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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