题解 | #分页#
分页
https://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.createElement("ul"); //TODO: 创建分页组件根节点 if (!this.el) return; this.el.innerHTML = this.html(); container.appendChild(this.el); this.el.className = this.total <=1 ? 'pagination hide' : 'pagination'; //TODO: 判断是否需要隐藏当前元素 function html() { if (this.total <= 1) return ''; let text = ""; if (this.total <= 5) { for(let i = 1; i <= total; i++) { text += `<li${i === this.current ? ' class="current"' : ''}>${i}</li>`; console.log(text) } } else { let i = this.current, j = i; text = `<li class="current">${this.current}</li>` while (j - i < 4) { if (i > 1) { text = `<li>${--i}</li>` + text; } if (j < total) { text = text + `<li>${++j}</li>`; } } if (i > 1) text = "<li>首页</li>" + text; if (j < this.total) text = text + "<li>末页</li>"; } //TODO: 生成组件的内部html字符串 return text; } 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(); }; }