题解 | #分页#

分页

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

全部评论

相关推荐

28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务