2016-07-26 35 views
0

我试图用30步增量创建一个for-loop。这样做的目的是希望在不使用任何插件的情况下将其用于非常简单和原始的分页。Javascript - 用30步增量创建一个for循环

首先我有一个无序的HTML列表:

<ul id="pagination"></ul> 

这是我用它来填充列表,并设置元素的属性代码。为了解决这个问题,使用了data-skipdata-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 

我该如何做到这一点?我觉得我快到了,但我不明白。如果需要其他细节,请告诉我们谢谢!

+1

'for(var c = 1; c <= intervalo; c + = 30){'??? – Rayon

+0

我可能过度简化了这个,但是... 'var skip =(c * 30) - 30 + 1;' – Hodrobond

+0

我已经试过了,但是这样会更加困难(我认为)列表。谢谢! – cubanGuy

回答

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)); 
2

30,而不是c++只是增加:

for (var c = 1; c <= total; c+=30) 
+0

我认为你的意思是(var c = 1; c <= total; c + = 30),对吗?您提供的循环只能将'li'添加到列表中。 – cubanGuy

+0

好吗?我只是努力工作,你已经有 –

+0

我相信。如果想一想,'intervalo'是将'var intervalo = Math.ceil(total/30)'分开的结果,所以在这种情况下它等于'4',总共有115个元素。无论如何,谢谢你。 – cubanGuy