一、实现
1.引用
<script>
$('.demo').page({
size: 10,
current: 1,
allPage: 10,
changePage: function (page, size) {
console.log(page, size)
}
});
</script>
2.原代码
(function(){
function TurnPage(options,wrap){
this.wrap = wrap;
this.size = options.size || 5;
this.current = options.current || 1;
this.allPage = options.allPage || (options.allSize ? Math.ceil(options.allSize / this.size) : 1);
this.changePage = options.changePage || function () {};
};
TurnPage.prototype.init = function () {
if (this.current > this.allPage) {
alert('当前页码大于总页数');
} else {
this.fillHtml();
this.bindEvent();
}
};
TurnPage.prototype.bindEvent = function(){
var self = this;
$('.my-page-prev',this.wrap).click(function(){
self.current --;
self.change();
});
$('.my-page-next',this.wrap).click(function(){
self.current ++;
self.change();
});
$('.my-page-num',this.wrap).click(function(){
self.current = parseInt($(this).text());
self.change();
});
$('.my-page-size-inp').change(function(){
console.log($(this).val());
self.size = parseInt($(this).val());
self.current = 1;
self.change();
});
};
TurnPage.prototype.change = function () {
this.fillHtml();
this.bindEvent();
this.changePage(this.current, this.size);
};
TurnPage.prototype.fillHtml = function(){
$(this.wrap).empty();
var myPageDiv = $('<div class="my-page"></div>');
var pageSizeDiv = $('<div class="my-page-size">每一页条数:<input class="my-page-size-inp" type="number" min=1 max=50 value=' + this.size + ' /></div>')
var myTurnPage = $('<ul class="my-turn-page"></ul>');
if(this.current > 1){
$('<li class="my-page-prev">上一页</li>').appendTo(myTurnPage);
};
$('<li class="my-page-num">1</li>').appendTo(myTurnPage).addClass(this.current == 1 ? 'current-page': '');
if(this.current -3 > 1){
$('<span>...</span>').appendTo(myTurnPage);
}
for(var i = this.current - 2;i <= this.current + 2;i ++){
if(i > 1 && i < this.allPage){
$('<li class="my-page-num"></li>').text(i).appendTo(myTurnPage).addClass(this.current == i ? 'current-page': '');
}
};
if(this.current + 3 < this.allPage){
$('<span>...</span>').appendTo(myTurnPage);
};
this.allPage != 1 && $('<li class="my-page-num"></li>').text(this.allPage).appendTo(myTurnPage).addClass(this.current == this.allPage ? 'current-page': '');
if(this.current < this.allPage){
$('<li class="my-page-next">下一页</li>').appendTo(myTurnPage);
};
myPageDiv.append(pageSizeDiv).append(myTurnPage).appendTo(this.wrap);
};
$.fn.extend({
page: function (options) {
var obj = new TurnPage(options,this);
obj.init();
}
})
})()