模仿某网站JavaScript分页控件
时间:2010-08-17 来源:版主
先上图:代码中有注释
代码function Paging(container, allCount, everyCount, showCount, GetDataFunction) {
this.container = container;
this.allCount = allCount;
this.everyCount = everyCount;
this.showPageCount = showCount;
this.GetDataFunction = GetDataFunction;
this.current = 1; this.start = 0; this.end = 0; this.total = 1;
}
Paging.prototype = {
initialize: function () {//初始化必要信息(current-->当前页、total-->总页数、start-->起始页、end-->结束页)
this.total = this.allCount % this.everyCount == 0 ? this.allCount / this.everyCount : parseInt(this.allCount / this.everyCount + 1);
this.start = this.current - this.showPageCount / 2 < 1 ? 1 : this.current - this.showPageCount / 2;
this.end = this.start + this.showPageCount > this.total ? this.total : this.start + this.showPageCount - 1;
},
create: function () { //创建分页控件(这时需要用到container属性,它表示分页控件放置的容器)
this.initialize();
this.GetDataFunction(this.current, this.everyCount);
document.getElementById(this.container).innerHTML = "";
if (this.total > 1) { //总页数大于1页时才创建分页控件
if (this.current > 1) {
this.createI("|<", "至首页", "first", -1);
this.createI("<<", "上一页", "up", -1);
}
for (var i = this.start; i <= this.end; i++) {
this.createI(i, "至第" + i + "页", i, i);
}
if (this.current < this.total) {
this.createI(">>", "下一页", "down", -1);
this.createI(">|", "至尾页", "last", -1);
}
}
},
createI: function (text, title, type, focus) {//超链接的属性(文字、Title、翻页的类型(上、下、首、尾)、焦点)
var input = document.createElement("input");
input.type = "button";
input.value = text;
input.title = title;
if (this.current == focus) input.style.background = "#FFFFFF";
var parent = this;
input.onclick = function () {
if (focus == parent.current) return false;
if (type == "first") parent.current = 1;
if (type == "up") parent.current--;
if (!isNaN(type)) parent.current = type;
if (type == "down") parent.current++;
if (type == "last") parent.current = parent.total;
parent.create();
}
document.getElementById(parent.container).appendChild(input);
}
}
使用方法:
代码var load = function () {
//参数依次为:容器ID、总数据行数、每页显示的数据条数、显示分页按钮的个数、获取数据的函数
var p = new Paging("name", 12345, 5, 11, GetData);
p.create();
}
//注意定义获取数据的函数时有两个参数:一个为当前页、一个每页显示的数据条数(后台查询数据库时需要使用)
var GetData = function (current, everyCount) {
}
//调用就可以了
window.onload = load;
谢谢大家,欢迎大家批评指正,有不明白的地方请留言,谢谢啦!
相关阅读 更多 +