题解 | #分页#

分页

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 = 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();
        }
      }

全部评论

相关推荐

预计下个星期就能开奖吧,哪位老哥来给个准信
华孝子爱信等:对接人上周说的是这周
点赞 评论 收藏
分享
10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务