这是我的代码:
var pages = Math.ceil(allItems / itemsPerPage);
var pagesArray = [];
for(var i = 0; i < pages; i++){
pagesArray.push(i);
}
var show = 3;
var offset = pageCounter + show;
var showPages = pagesArray.slice(pageCounter, offset);
for(var h = 0; h < showPages.length; h++){
if(pageCounter == showPages[h]){
selectedPageClass = 'selected';
}else{
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
}
我现在的问题是:
如果我有这个数组["1","2","3","4","5"]
我在页面上的第一步&#34; 0&#34;它应该是:
1(selected) 2 3
2(selected) 3 4
3(selected) 4 5
4(selected) 5
5(selected)
但我想要的是:
1(selected) 2 3
2(selected) 3 4
3(selected) 4 5
3 4(selected) 5
3 4 5(selected)
答案 0 :(得分:1)
http://codepen.io/anon/pen/JbBYva
您可以更新顶部的变量,pageCounter是基于0的。
//editable variables
var pages = 5;
var pageCounter = 0;
var show = 3;
//calculation
var pagesArray = [];
for(var i = 1; i <= pages; i++){
pagesArray.push(i);
}
var offset = pageCounter + show;
var showPages = pagesArray.slice(Math.min(pages - show, pageCounter), offset);
for(var h = 0; h < showPages.length; h++){
if(pageCounter + 1 == showPages[h]){
selectedPageClass = 'selected';
}else{
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
}
答案 1 :(得分:1)
你应该这样做showPages
:
var showPages = pagesArray.slice(Math.min(pageCounter, pages- show), offset);
见下面的演示:
var pages = 10,
pageCounter = 0;
var pagesArray = [];
for (var i = 0; i < pages; i++) {
pagesArray.push(i);
}
var show = 3;
function paginate() {
$(".pagination").empty();
var offset = pageCounter + show;
var showPages = pagesArray.slice(Math.min(pageCounter, pages - show), offset);
for (var h = 0; h < showPages.length; h++) {
if (pageCounter == showPages[h]) {
selectedPageClass = 'selected';
} else {
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass + "'>" + showPages[h] + "</a>");
}
}
// initialize
paginate();
// turn pages
$('#counter').click(function() {
if (pageCounter >= pages)
return;
pageCounter++;
paginate();
});
// restart pagination
$('#restart').click(function() {
pageCounter = 0;
paginate();
});
&#13;
.selected {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pagination"></div>
<button id="counter">Turn a page</button>
<button id="restart">Restart</button>
&#13;