我尝试创建for-loop
,增量为30步。这样做的目的是希望在不使用任何插件的情况下将其用于非常简单和原始的分页。
首先,我有一个无序的HTML列表:
<ul id="pagination"></ul>
这是我用来填充列表的代码,并设置元素的属性。为了这个问题,使用了data-skip
和data-top
,但实际上它们稍后会被添加到url
以进行REST调用以获取数据。
var total = 115;
var intervalo = Math.ceil(total / 30);
var pagination = document.getElementById('pagination');
for (var c = 1; c <= intervalo; c++) {
var top = c * 30;
var skip = (c * 30) - 30;
console.log('&$skip=' + skip + ' &$top=' + top);
var li = document.createElement('li');
li.id = c;
li.setAttribute('data-skip', '&$skip=' + skip);
li.setAttribute('data-top', '&$top=' + top);
var a = document.createElement('a');
a.href = '#';
a.textContent = c;
li.appendChild(a);
pagination.appendChild(li);
}
以上代码在控制台中返回:
&$skip=0 &$top=30
&$skip=30 &$top=60
&$skip=60 &$top=90
&$skip=90 &$top=120
但这就是问题所在。如果您发现&$skip
始终与之前的&$top
匹配。实际上我需要的是返回类似的东西:
&$skip=0 &$top=30
&$skip=31 &$top=60
&$skip=61 &$top=90
&$skip=91 &$top=120
我怎样才能做到这一点?我觉得我几乎就在那里,但我没有做对。如果需要任何其他细节,请告诉我们谢谢!
答案 0 :(得分:2)
只需增加30而不是c++
:
for (var c = 1; c <= total; c+=30)
答案 1 :(得分:0)
我想我明白了。它可能不是最佳选择,但它现在适用于我。希望能帮助别人,甚至有人会提供比我更好的答案。我创建了一个数组,之后我操纵了。
var total = 115;
var intervalo = Math.ceil(total / 30);
var pagination = document.getElementById('pagination');
var range = [];
for (var c = 1; c <= intervalo; c++) {
var top = c * 30;
var skip = (c * 30) - 30;
range.push({
skip: skip,
top: top
});
// console.log('&$skip=' + skip + ' &$top=' + top);
var li = document.createElement('li');
li.id = c;
li.setAttribute('data-skip', '&$skip=' + skip);
li.setAttribute('data-top', '&$top=' + top);
var a = document.createElement('a');
a.href = '#';
a.textContent = c;
li.appendChild(a);
pagination.appendChild(li);
}
console.log(JSON.stringify(range));
for (var r = 1; r < range.length; r++) {
range[r].top = range[r].top - 1;
}
console.log(JSON.stringify(range));