题解 | #分页#
分页
http://www.nowcoder.com/questionTerminal/71da71df9d1c4af9b8dc056213473ba7
js简洁代码
function Pagination(container, total, current) {
this.total = total;
this.current = current;
this.html = html;
this.val = val;
// 创建分页组件根节点,是创建一个新节点,不是获得已存在的节点
this.el = document.createElement('ul');
if (!this.el) return;
this.el.innerHTML = this.html();
container.appendChild(this.el);
// 判断是否需要隐藏当前元素
this.el.className = this.total <= 1 ? 'pagination hide': 'pagination';
function html() {
// 小于等于1,不需要显示
if (this.total <= 1) return '';
// 小于5,直接渲染输出
let liList = '';
if (this.total <= 5) {
for (let i = 1; i <= this.total; i++) {
liList += `<li ${i === current ? 'class = "current"' : '' }>${i}</li>`;
}
return liList;
}
// 大于5,找到左边界和右边界,并考虑是否需要首末页提示
// 左边界最小为1, 右边界最大为total
let left = Math.max(this.current - 2, 1);
let right = Math.min(this.current + 2, this.total);
// 长度不足5,补到5,注意不能超过边界
while (right - left < 4) {
left === 1 ? right++ : left--;
}
// 渲染5个li
for (let i = left; i <= right; i++) {
liList += `<li ${i === current ? 'class = "current"' : '' }>${i}</li>`;
}
// 拼接首末页,使用模板表达式简化代码
liList = `${left !== 1 ? '<li>首页</li>' : ''}${liList}${right !== this.total ? '<li>末页</li>' : ''}`;
return liList;
}
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();
};
}