To solve this you can build the column values using their ordinal positions.(为了解决这个问题,您可以使用列的顺序位置来构建列值。)
As this is for a calendar you can assert that a grid of 6*6 cells (or 7*5 in your example) is enough to fit all 31 days in, no matter where the starting position is.(因为这是用于日历的,所以您可以断言,无论起始位置在哪里,一个6 * 6单元格(在您的示例中为7 * 5)的网格足以容纳所有31天。) As such you can use two loops and calculate the day number based on the current row/col, like this(这样,您可以使用两个循环并根据当前行/列计算天数,如下所示)
var $table = $('<table>', { 'class': 'table-calendar table table-hover text-center table-calendar' }).appendTo('.table-responsive'); var $tbody = $('<tbody>').appendTo($table); var rowCount = 7, colCount = 5; var html = ''; for (var row = 0; row < rowCount; row++) { html += '<tr>'; for (var col = 0; col < colCount; col++) { var day = (row + 1) + (col * rowCount); if (day < 32) html += `<td>${day}</td>`; } html += '</tr>'; } $tbody.append(html);
td { padding: 5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="table-responsive"></div>
This logic can then be easily tweaked to move the starting position based on day of week and also the number of days in the given month.(然后,可以根据星期几以及给定月份的天数轻松调整此逻辑以移动起始位置。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…