如何计算需要多少行和列

问题描述 投票:0回答:3

我想用Javascript生成一个表。我想给它一个数字,这就是创建了多少个单元格。但总有3列(每行3张)

有人可以帮我解决这个问题吗?我想我需要使用模数运算符,但我不确定如何正确使用它。

我不想要任何额外的细胞。我可以毫无问题地计算行,但如果有意义,我不希望这些行有额外的单元格。因此,一旦细胞被制成,即使它的1或2个细胞短,该行也会结束。

我现在有这个:

rows = ?? //Not sure how to calculate this
columns = 3;
str = "";
str += '<table border="1" cellspacing="1" cellpadding="5">';

for(i = 0; i < rows; i++){
   str += '<tr>';
   for (j = 0; j < columns; j++){
      str += '<td>' +  (i + j) + '</td>';
   }
   str += '</tr>';
}

str += '</table>';
javascript html-table modulo
3个回答
1
投票

我希望以下代码能够满足您的需求。

var numOfPics = 100; // Number of Pictures
var columns = 3, rows = Math.ceil(numOfPics / columns), content = "", count = 1;
content = "<table border='1' cellspacing='1' cellpadding='5'>";
for (r = 0; r < rows; r++) {
   content += "<tr>";
   for (c = 0; c < columns; c++) {
      content += "<td>" + count + "</td>";
      if (count == numOfPics)break;  // here is check if number of cells equal Number of Pictures to stop
      count++;
   }
   content += "</tr>";
}
content += "</table>";

document.body.innerHTML = content; // insert `content` value into body of page

0
投票

你知道有多少个细胞。因此,您将单元格数除以列数以获取行数。如果没有准确数量的细胞来填充行,Math.ceil()会进行舍入。

rows = Math.ceil(total_num_cells / 3);


0
投票

假如你有多少张图片作为numPictures: - 那么

var numRows = Math.ceil(numPictures/3); 
© www.soinside.com 2019 - 2024. All rights reserved.