自定义分页表格的实现
闲来无事,自己分装了一个支持分页的表格,支持本地数据,支持ajax读取server数据。
代码比较清晰,不做过多解释。
调用方法很简单
var tb1 = new ITable("test_tb", 2); //第一个参数是整个控件元素div的id,第二个参数是每个表格数据条数 tb1.load(null ,[{name:"zhangsan", age:1}, {name:"lis", age:2}]); //当使用ajax读取数据时传入第一个参数,代表ajax的请求地址。当使用本地数据时,第一个参数置空,第二个参数是本地数据
直接上截图
代码可直接在本地运行:
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function ITable(id, limit) {
this.id = id;
this.start = 0;
this.limit = limit;
this.data = null;
this.url = null;
this.localdata = null;
this.total = null;
this.init();
}
ITable.prototype.init = function() {
var thisObj = this;
$("#" + this.id + " .first_btn").on("click", function () {
thisObj.first();
thisObj.setPageNo();
});
$("#" + this.id + " .next_btn").on("click", function () {
thisObj.next();
thisObj.setPageNo();
});
$("#" + this.id + " .prev_btn").on("click", function () {
thisObj.prev();
thisObj.setPageNo();
});
$("#" + this.id + " .last_btn").on("click", function () {
thisObj.last();
thisObj.setPageNo();
});
$("#" + this.id + " .set_page input").on("blur", function () {
var val = parseInt($(this).val());
if(val > 0 && val <= Math.ceil(thisObj.total / thisObj.limit)) {
thisObj.start = (val - 1) * thisObj.limit;
}
thisObj.load(thisObj.url, thisObj.localdata);
});
}
ITable.prototype.setdata = function() {
var result = "";
$.each(this.data, function(i, item) {
result += "<tr>";
$.each(item, function(key, value) {
result += "<td>" + value+ "</td>";
});
result += "</tr>";
});
$("#" + this.id + " table tbody").html(result);
}
ITable.prototype.setPageNo = function() {
$("#" + this.id + " .set_page input").val(this.start / this.limit + 1);
}
ITable.prototype.load = function(url, localdata) {
this.url = url;
this.localdata = localdata;
if(localdata) {
this.total = localdata.length;
if(localdata.length > this.start + this.limit) {
this.data = localdata.slice(this.start, this.start + this.limit);
} else if(localdata.length > this.start) {
this.data = localdata.slice(this.start);
} else {
return;
}
this.setdata();
} else {
var thisObj = this;
$.getJSON(url, {start:this.start, limit: this.limit}, function(json){
thisObj.data = json.data.content;
thisObj.total = json.data.totalElements;
thisObj.setdata();
});
}
}
ITable.prototype.next = function() {
if(this.start < this.total - this.limit) {
this.start += this.limit;
this.load(this.url, this.localdata);
}
}
ITable.prototype.prev = function() {
if(this