我试图生成分页按钮。
我希望按钮看起来像这样:
粗体数字是所选页面,7是最高页面。
我的当前功能会生成此内容,直到您在最后3页上显示。
[1, 2, 3, "...", 7]
[2, 3, 4, "...", 7]
[3, 4, 5, "...", 7]
[4, 5, 6, "...", 7]
[5, 6, 7]
[6, 7]
[7]
我希望它看起来像:
[1, 2, 3, "...", 7]
[2, 3, 4, "...", 7]
[3, 4, 5, "...", 7]
[4, 5, 6, "...", 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
Javascript :
var test = function (count, current) {
this.pageCountArray = [];
var shownPageNumbers = 3;
for (var i = current; i <= count; i++) {
if (this.pageCountArray.length < shownPageNumbers) {
this.pageCountArray.push(i);
}
else {
this.pageCountArray.push('...');
this.pageCountArray.push(count);
break;
}
}
console.log(this.pageCountArray);
}
用法:
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
console.clear();
var test = function (count, current) {
this.pageCountArray = [];
var shownPageNumbers = 3;
for (var i = current; i <= count; i++) {
if (this.pageCountArray.length < shownPageNumbers) {
this.pageCountArray.push(i);
}
else {
this.pageCountArray.push('...');
this.pageCountArray.push(count);
break;
}
}
console.log(this.pageCountArray);
document.write(JSON.stringify(this.pageCountArray))
}
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
&#13;
答案 0 :(得分:6)
以下是我将如何实现它:
function pageNumbers(count, current) {
var shownPages = 3;
var result = [];
if (current > count - shownPages) {
result.push(count - 2, count - 1, count);
} else {
result.push(current, current + 1, current + 2, '...', count);
}
return result;
}
答案 1 :(得分:2)
您的问题是,您只是将数组从current
填充到count
。因此,当您获得高于current
的{{1}}值时,您需要从count - (shownPageNumbers - 1)
而不是仅仅count - (shownPageNumbers - 1)
开始for循环,以便显示正确的页码数量。
您可以在for循环检查之前添加if语句if(current&gt;(count - (shownPageNumbers - 1))并将当前更新为当前,或者在for循环中i = min(current,(count - ( shownPageNumbers - 1))