刚写的一个js分页类,未优化

来源:互联网 发布:大数据建模工程师 编辑:程序博客网 时间:2024/04/28 08:44

以前也写过,很久以前了,写的很长,并且使用起来也不灵活。这次搞了个灵活版的。

/* * SunPage --自定义分页类,仅获取分页的html代码,简单应用 * Sunbt 2015-5-4 * v1.0 * @param current_page int 当前页 * @param totle_page int 总页数 * @param take_num int 当前页左右携带页码数 * @param func_obj obj 分页实现函数*/var SunPage = function(current_page, totle_page, take_num, func_obj) {    this.current_page = current_page;    this.totle_page = totle_page;    this.take_num = take_num;    this.func_obj = func_obj;    this.page_html = "";    this.init();}SunPage.prototype = {    constructor : SunPage,    init : function() {        var start = this.current_page - this.take_num < 2 ? 2 : this.current_page - this.take_num, //起始索引            _end_patch = start - (this.current_page - this.take_num), //右侧补码            _end = this.current_page + this.take_num + _end_patch, //计算结束索引            end = _end < this.totle_page ? _end : this.totle_page - 1, //实际结束索引            _start_patch = _end -  end; //左侧补码        if (_start_patch > 0 && _end_patch == 0) { //如果有左侧补码,并且右侧补码为0,进行左侧侧补码            start -= _start_patch;            start = start < 2 ? 2 : start;        }        this.func_obj.previous.call(this); //上一页        this.func_obj.common.call(this, 1); //第一页        if (start == 3) {            this.func_obj.common.call(this, 2); //开始索引为三,第二页直接显示        } else if(start > 3) {            this.func_obj.ellipsis.call(this); //开始索引大于三,显示省略号        }        for (var i = start; i <= end; i++) {            this.func_obj.common.call(this, i); //从索引开始到结束        }        if (end < this.totle_page - 2) {            this.func_obj.ellipsis.call(this); //结束索引为总页码减二,则显示总页码减一的页码        } else if(end == this.totle_page - 2) {            this.func_obj.common.call(this, this.totle_page - 1); //        }        this.func_obj.common.call(this, this.totle_page);        this.func_obj.next.call(this);    },    toString :function() {        return this.page_html;    }}

嘿嘿,灵活也要付出代价的,就是调用的时候会复杂些。下面是调用方式:

var sunpage = new SunPage(6, 20, 2, {    previous : function() {        if(this.current_page == 1) {            this.page_html += '<li class="k"><span>上一页</span></li>';        } else {            this.page_html += '<li class="k"><a href="?page=' + (this.current_page - 1) + '">上一页</a></li>';        }    },    next : function() {        if(this.current_page == this.totle_page) {            this.page_html += '<li class="k"><span>下一页</span></li>';        } else {            this.page_html += '<li class="k"><a href="?page=' + (this.current_page + 1) + '">下一页</a></li>';        }    },    ellipsis : function() {        this.page_html += '<li class="ellipsis">...</li>';    },    common :function(num){        if(num == this.current_page) {            this.page_html += '<li><span>' + num + '</span></li>';        } else {            this.page_html += '<li><a href="?page=' + num + '">' + num + '</a></li>';        }    }});document.write(sunpage.toString());

很多地方都没做校验的,有问题后再修改吧。目前测试没问题。

1 0
原创粉丝点击