我写的好复杂,好多代码都重复的
function Pagination(container, total, current) { this.total = total; this.current = current; this.html = html; this.val = val; this.el = null; //TODO: 创建分页组件根节点 this.el = document.createElement("ul"); if (!this.el) return; console.log(this.el, "234"); this.el.innerHTML = this.html(); container.appendChild(this.el); console.log(container, "123"); this.el.className = this.total < 1 ? "pagination hide" : "pagination"; //TODO: 判断是否需要隐藏当前元素 function html() { if (this.total <= 1) return ""; //TODO: 生成组件的内部html字符串 let liArr = []; if (this.total <= 5) { liArr = [] for (let i = 1; i <= this.total; i++) { let oli = `<li>${i}</li>`; if (i === this.current) { oli = `<li class="current">${i}</li>`; } liArr.push(oli); } return liArr.join(" "); } else if (this.current > 3 && this.current < this.total - 2) { liArr = [] for (let i = this.current - 3; i <= this.current + 2; i++) { let oli = `<li>${i}</li>`; if (i === this.current) { oli = `<li class="current">${i}</li>`; } liArr.push(oli); } liArr[0] = `<li>首页</li>`; liArr[this.total - 1] = `<li>末页</li>`; return liArr.join(" "); } else if (this.current <= 3&& this.total>5) { liArr = [] for (let i = 1; i <= 5; i++) { let oli = `<li>${i}</li>`; if (i === this.current) { oli = `<li class="current">${i}</li>`; } liArr.push(oli); } liArr[6] = `<li>末页</li>`; return liArr.join(" "); }else if (this.current >=this.total-2&& this.total>5) { liArr = [] for (let i = this.total-5; i <= this.total; i++) { let oli = `<li>${i}</li>`; if (i === this.current) { oli = `<li class="current">${i}</li>`; } liArr.push(oli); } liArr[0] = `<li>首页</li>`; return liArr.join(" "); } } 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(); } }