function Pagination(container, total, current) {
this.total = total;
this.current = current;
this.html = html;
this.val = val;
this.el = null; //TODO: 创建分页组件根节点
this.el = document.querySelector('.pagination');
if (!this.el) return;
this.el.innerHTML = this.html();
container.appendChild(this.el);
this.el.className = ''; //TODO: 判断是否需要隐藏当前元素
if (this.total < 1) {
this.el.className = "hide";
}
function html() {
if (this.total <= 1) return '';
let total = this.total;
let cur = this.current;
let html = "";
if (total <= 5) {
for (let i = 1; i <= total; ++i) {
html += `\n<li ${i == cur ? 'class="current"' : ""}>${i}</li>`
}
if (total == 5) {
html += `<li>末页</li>`;
}
// console.log("case 1:", html);
} else {
let pre = cur - 2;
let suf = cur + 2;
let start = pre;
let end = suf;
if (pre < 1) {
start = 1;
end = suf + (1 - pre);
}
if (suf > total) {
start = start - (suf - total);
end = total;
}
if (pre > 1) {
html += `<li>首页</li>`;
}
for (let i = start; i <= end; ++i) {
html += `\n<li ${i == cur ? 'class="current"' : ""}>${i}</li>`
}
if (suf < total) {
html += `<li>末页</li>`;
}
// console.log("case 2:", html);
}
//TODO: 生成组件的内部html字符串
return html;
}
function val(current) {
if (arguments.length === 0) return this.current;
if (current < 1 || current > this.total || current === this.current) return;
this.current = current;
this.el.innerHTML = this.html();
};
}