题解 | #分页#

分页

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");
      this.el.classList.add("pagination");
      if (!this.el) return;

      this.el.innerHTML = this.html();
      container.appendChild(this.el);
      if (this.el.innerHTML == "") {
        this.el.classList.add("hide"); //TODO: 判断是否需要隐藏当前元素
      }

      function html() {
        if (this.total <= 1) {
          return "";
        } else if (this.total <= 5) {
          let str = "";
          for (let i = 1; i <= total; i++) {
            if (this.current == i) {
              str += `<li class="current">${i}</li>`;
            } else {
              str += `<li>${i}</li>`;
            }
          }
          return str;
        } else if (this.current + 2 <= total && this.current - 2 >= 1) {
          let str = "";
          if (this.current - 2 > 1) {
            str += `<li>首页</li>`;
          }
          for (let i = current - 2; i <= current + 2; i++) {
            if (this.current == i) {
              str += `<li class="current">${i}</li>`;
            } else {
              str += `<li>${i}</li>`;
            }
          }
          if (this.current + 2 < this.total) {
            str += `<li>末页</li>`;
          }
          return str;
        } else if (this.current + 2 > total) {
          let str = "";
          str += `<li>首页</li>`;
          for (let i = total - 4; i <= total; i++) {
            if (this.current == i) {
              str += `<li class="current">${i}</li>`;
            } else {
              str += `<li>${i}</li>`;
            }
          }
          return str;
        } else {
          let str = "";
          for (let i = 1; i <= 5; i++) {
            if (this.current == i) {
              str += `<li class="current">${i}</li>`;
            } else {
              str += `<li>${i}</li>`;
            }
          }
          str += `<li>末页</li>`;
          return str;
        }

        //TODO: 生成组件的内部html字符串
      }
    }

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务