我愿意做一些非常基本的事情;但是,我坚持了下来。 我有一个表格,它有5行,每行有4个数字。
应该如下:
1 | 2 | 3 | 4
5 | 6 | 7 | 8
9 | 10 | 11 | 12
依此类推......最多20个
目前,我正在运行2 for for循环以完成表格显示,但错误的数字(每行只显示1到4)我相信我有一个逻辑问题。
以下是它现在的样子:
1 | 2 | 3 | 4
1 | 2 | 3 | 4
1 | 2 | 3 | 4
代码:
var div, rows, linksInRows, row, col, htmlButton;
div = $('div.container');
row = '<div class="row"></div>';
rows = 5;
linksInRows = 4;
for (i = 0; i < rows; i++) {
div.append(row);
}
for (i = 0; i < linksInRows; i++) {
col = $('div.row');
htmlButton = '<div class="col"><a class="btn btn-color" href="#" role="button">'+(i+1)+'</a></div>'
col.append(htmlButton)
}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
&#13;
答案 0 :(得分:-1)
你很亲密。一些修改如下:
嵌套循环,以便您可以有效地访问每行中的每个元素
仅抓取 附加的最后一个div,目前您抓取所有div.row
您的链接号等于行数乘以每行的链接数加上行中当前链接的索引加上1从1开始而不是从0开始。
在代码中,看起来像这样:linkNumber = i * linksInRows + j + 1;
var div, rows, linksInRows, row, col, htmlButton;
div = $('div.container');
row = '<div class="row"></div>';
rows = 5;
linksInRows = 4;
// nest the loops instead of making them separate
for (i = 0; i < rows; i++) {
div.append(row);
for (j = 0; j < linksInRows; j++) {
// we only want the most recently created div.row, not all of them
col = $('.container .row').last();
// take current i * the number of links in each row, so for the first
// row you get 0-3, second row is 4-7, etc. then add 1 to start at 1
// instead of 0
var linkNumber = i * linksInRows + j + 1;
htmlButton = '<div class="col"><a class="btn btn-color" href="#" role="button">Link '+linkNumber+'</a></div>'
col.append(htmlButton)
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>