剛寫的一個js分頁類,未最佳化
以前也寫過,很久以前了,寫的很長,並且使用起來也不靈活。這次搞了個靈活版的。
/* * 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 += '
上一頁
'; } else { this.page_html += '
上一頁
'; } }, next : function() { if(this.current_page == this.totle_page) { this.page_html += '
下一頁
'; } else { this.page_html += '
下一頁
'; } }, ellipsis : function() { this.page_html += '
...
'; }, common :function(num){ if(num == this.current_page) { this.page_html += '
' + num + '
'; } else { this.page_html += '