题解 | #分页#
分页
http://www.nowcoder.com/practice/71da71df9d1c4af9b8dc056213473ba7
function Pagination(container, total, current) {
this.total = total;
this.current = current;
this.html = html;
this.val = val;
this.el = document.querySelector('.pagination'); //TODO: 创建分页组件根节点
if (!this.el) return;
this.val()
this.el.innerHTML = this.html();
container.appendChild(this.el);
// this.el.className = '';
//TODO: 判断是否需要隐藏当前元素
if (total <= 1) {
this.el.classList.add('hide')
}
function html() {
var liList = ''
if (this.total <= 1){
return '';
}
var start = 1;
var end = total > 5 ? 5 :total;
var head = `<li>首页</li>`
var foot = `<li>末页</li>`
if (current-2 > 1 && current+2 < total) {
// 有首页有末页
start = current-2
end = current+2
} else if (current-2 > 1 && current+2 >= total) {
// 有头无尾
start = total-4
end = total
foot = ''
} else if (current-2 <= 1 && current+2 < total) {
// 无头有尾
start = 1
end = 5
head = ''
} else {
// 无头无尾
start = 1
end = total
head = ''
foot = ''
}
liList += head
for (let index=start; index <= end;index++) {
index===current ? liList += `<li class = 'current'>${index}</li>` : liList += `<li>${index}</li>`
}
liList += foot
console.log(liList, 'liList')
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();
};}
查看5道真题和解析