简体   繁体   English

我可以在已经存在于forloop中的.append()中获得一个forloop吗?

[英]Can I get a forloop in an .append(), that already is in a forloop?

I'm trying to create a Table based on "width"(columns) and "height"(rows) but I just can't get it right. 我正在尝试基于“宽度”(列)和“高度”(行)创建表格,但我做对了。 So is there Something wrong with my code? 那么我的代码出问题了吗?

Code: 码:

for(var i=0;i<width;i++){
        $('#map').append(
            '<tr>'+
                for(var e=0;e<height;e++){

                }
            +'</tr>'
        );
    };

Your code is invalid, you can't have a for loop there. 您的代码无效,那里没有for循环。 Try rearranging it a bit. 尝试重新排列一下。

var html;
for(var i=0;i<width;i++){
    html = '<tr>';
    for(var e=0;e<height;e++){
        html += "<td>foo"+e+"</td>";
    }
    html +='</tr>'
    $('#map').append(html);
};

or even better: 甚至更好:

var html = "";
for(var i=0;i<width;i++){
    html += '<tr>';
    for(var e=0;e<height;e++){
        html += "<td>foo"+e+"</td>";
    }
    html +='</tr>';
};
$('#map').append(html);

Programmatically create the <tr> element and append the <td> elements to it instead. 以编程方式创建<tr>元素,并将<td>元素附加到该元素。

var table = [];
for(var i = 0, $tr; i < height; i++){
  $tr = $("<tr/>");
  for(var j = 0; j < width; j++){
    $tr.append("<td/>");
  )
  table.push($tr);
}
$map.append(table);

UPDATE: Optimized for DOM access. 更新:针对DOM访问进行了优化。

You can make it like this: 您可以这样:

for(var i=0; i < height; i++){
  var row = "<tr>";
  for(var j=0; j < width; j++){
    row += "<td>Something data</td>";
  }
  row += "</tr>";
  $('#map').append(row)
}

The jQuery way to do what you're doing is like so: jQuery完成您正在做的事情的方式是这样的:

var $table = $('<tbody />');

for(var i = 0; i < width; i++){
  $tr = $("<tr/>");
  for(var e = 0; e < height; e++){
    $tr.append("<td/>");
  );
  $table.append($tr);
};

$('#map').append($table);

That way you are only accessing the DOM once . 这样,您只需访问DOM 一次

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

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