DataTable.js

if (typeof(webroot) == "undefined") var webroot = "";


function DataTable(tableID,url){
this.tableID = tableID;
this.url = url;
this.message = {};
this.pageSize = 10;//每页条数
this.curPage = 1;//当前页
this.spanInterval = 3;//当前索引与旁边间隔几页
this.data;
this.total;//总条数
this.totalPage;
this.requestMethod="get";
this.options={};
this.parameter="";
this.queryString="";
this.columnNames=[];
this.columnClass="";
this.appendData = false;
this.cacheData = [];
this.cachePage = true;
var _table = this;
this.getCookie=function(name){
return jQuery.cookie(name);
},
this.setCookie=function(name,value){
jQuery.cookie(name,value);
},
this.cookieName=function(){
var url = document.location.href;
if (url.indexOf("#")>0) url = url.substring(0,url.indexOf("#"));
return url+"."+this.tableID+".PageIndex";
},
this.addHead=function(head){
   var thead = $('<thead></thead>');
   var tr = $('<tr></tr>'); 
   for(var i in head) {
    var temp = 0;
    var td = $('<td id="' + tableID + '_0_' + temp + '" class="'+this.columnClass+'" data-options="field:'+i+'"></td>');
    thead.append(tr.append(td.append(this.drawCell(head[i],0,'head'))));
    temp++;
   }
   $('#'+tableID+' thead').replaceWith(thead);
};
this.init=function(){
var opts = $("#"+this.tableID).attr("data-options");
if (opts) this.options = eval("({" + opts + "})");
if (this.options.rownumbers && !$("#"+this.tableID + " thead .rownumber").html()) {
$("#"+this.tableID + " thead td :first").before("<td class=\""+this.columnClass+" rownumber\" data-options=\"rownumber:true\" nowrap>&nbsp;</td>");
}
if (this.options.checkbox && !$("#"+this.tableID + " thead .checkbox").html()) {
$("#"+this.tableID + " thead td :first").before("<td class=\""+this.columnClass+" checkbox\" data-options=\"checkbox:true\"><input type=checkbox οnclick=toggleDataTableSelection('"+this.tableID+"',this)></td>");
}
if (this.options.pageSize) {
this.pageSize = this.options.pageSize;
}
var tds = $("#"+this.tableID + " thead td");
for (var i=0; i<tds.length; i++) {
var opts = $(tds[i]).attr("data-options");
if (opts) opts = eval("({" + opts + "})");
else opts = {};
var field = null;
if (opts) field =  opts.field;
this.columnNames[i] = field;
}
var pageNo = this.getCookie(this.cookieName());
if (pageNo != null && !isNaN(pageNo) && this.cachePage) {
this.curPage = pageNo;
}
this.getData();
this.setCookie(this.cookieName(), this.curPage);
};
this.reload=function(){//重新刷新本页
this.getData();
this.setCookie(this.cookieName(), this.curPage);
};
this.getData=function(){//取数
var params = "pageNum="+this.curPage+"&pageSize="+this.pageSize+this.parameter+this.queryString;
var reqData = params+"&t="+Math.random();
if (this.requestMethod == "post") {
reqData = {};
var pairs = params.split("&");
for (var i=0; i<pairs.length; i++) {
var values = pairs[i].split("=");
reqData[values[0]] = values[1];
}
reqData = JSON.stringify(reqData);
}
        $.ajax({type:_table.requestMethod,
        dataType:"json",
        contentType:"application/json; charset=utf-8",
        url: webroot+this.url,
    data:reqData,
            async:true, cache:false,
            beforeSend:function(){
            try{
            $.loading.showLoading();
            }catch(e){}
            },
            success: function(data){
            if (!data.responseBody) return;
            _table.data = data.responseBody.data;
            if (!_table.data) {
            $.message.alert("错误","加载失败:["+data.responseBody.status+"]"+data.responseBody.message);
            _table.data = [];
            } else {
            _table.total = data.responseBody.datasetSize;
            _table.totalPage = Math.ceil(_table.total / _table.pageSize);
            _table.showData();
            _table.setButtonStatus();
            _table.callback();
            }
            },
            complete:function(){
            try{
            $.loading.hideLoading();
            }catch(e){}
            },
            error: function(e){
            $.message.alert("错误","数据加载失败");
            }
        });
        
};
this.callback=function(){

};
this.setButtonStatus=function(){
try {
hideLinks();
} catch (e) {}
};
this.showData=function(){
if ($("#"+this.tableID + " thead :checkbox")) {
$("#"+this.tableID + " thead :checkbox").attr("checked", false);
}
var datas = [];
if (this.appendData) {
for(var i = 0; i < this.data.length; i ++ ){
    var loaded = false;
    for (var j=0; j<this.cacheData.length; j++) {
    if (this.cacheData[j].id == this.data[i].id)
    loaded = true;
    }
    if (!loaded) {
    this.cacheData.push(this.data[i]);
    datas.push(this.data[i]);
    }
   }
} else{
datas = this.data;
}
   var tbody = $('<tbody></tbody>'); 
   for(var i = 0; i < datas.length; i ++ ){
    tbody.append(this.getRowHtml(datas[i],i+1));
   }
   if (this.appendData) {
    $('#'+tableID+' tbody').append(tbody.html());
   } else {
    $('#'+tableID+' tbody').replaceWith(tbody);
   }
   //分页展示
   //this.curPage = 7;
//this.pageSize = 10;
//this.total = 1000;
   this.showNavi(this.curPage);
};
this.showNavi=function(intPageIndex){//tableID,当前页,总页数,隔间页数
intPageIndex = parseInt(intPageIndex);
var clickPageSize = this.pageSize;
var pageBar = $('#'+this.tableID+'_pagination');
if (pageBar == null) return;
var pageS = this.total;
if (pageS % this.pageSize == 0) pageS = pageS / this.pageSize;      
else pageS = parseInt(this.total / this.pageSize) + 1;         

$('#'+this.tableID+'_pagination').empty();
//只有一页数据的时候不显示分页控件
if (this.total < this.pageSize) return;
   //设置分页的格式  这里可以根据需求完成自己想要的结果             
var interval = parseInt(this.spanInterval); //设置间隔           
var start = Math.max(1, intPageIndex - interval); //设置起始页       
var end = Math.min(intPageIndex + interval, pageS);//设置末页

   //添加上一页                        
if (intPageIndex == 1){
pageBar.append("<span class='disabled'>上一页</span>");
}else {
var pre = $("<a href='javascript:void(0)' class='number' page='" + (parseInt(intPageIndex) - 1) + "'>上一页</a>").click(function () {  
_table.pageClick($(this).attr('page'),clickPageSize);
return false;                         
});                           
pageBar.append(pre);  
}

   //添加第一页                        
if (start > 1){
var first = $("<a href='javascript:void(0)' class='number' page='" + 1 + "'>1</a>").click(function () {   
_table.pageClick($(this).attr('page'),clickPageSize);
});                            
pageBar.append(first);
pageBar.append("<label>..&nbsp;</label>");
}

   //生成页码                  
for (var j = start; j < end + 1; j++) {
if (j == intPageIndex) {
var spanSelectd = $("<a href='javascript:void(0)' class='number current'>" + j + "</a>");     
pageBar.append(spanSelectd);
}else {
var a = $("<a href='javascript:void(0)' class='number'>" + j + "</a>").click(function () {   
_table.pageClick($(this).text(),clickPageSize);           
return false;
});                  
pageBar.append(a);
}


   //最后一页                  
if (end < pageS) {
var last = $("<a href='javascript:void(0)' class='number' page='" + pageS + "'>"+pageS+"</a>").click(function () {       
_table.pageClick($(this).attr("page"),clickPageSize);    
return false;                          
});           
pageBar.append("<label>..&nbsp;</label>");
pageBar.append(last); 
}

   //下一页             
if (intPageIndex * this.pageSize >= this.total ) {
pageBar.append("<span class='disabled'>下一页</span>");
}else {
var next = $("<a href='javascript:void(0)' class='number' page='" + (parseInt(intPageIndex) + 1) + "'>下一页</a>").click(function () {   
_table.pageClick($(this).attr("page"),clickPageSize);       
return false;                         
});                           
pageBar.append(next); 
}

};
this.getRowHtml=function(data,num) {
var tr = $('<tr ></tr>'); 
var tds =  $("#"+this.tableID+" thead td");
for (var i=0; i<tds.length; i++) {
var td = $('<td id="' + this.tableID + '_' + num + '_' + i + '" class="'+this.columnClass+'"></td>');
var opts = tds[i].getAttribute("data-options");
if (!opts) opts="";
opts = eval("({"+opts+"})");
var field = opts.field;
if(opts.checkbox){
$(td).addClass("checkbox");
$(td).css("width","20px");
tr.append(td.append('<input class="rowselect" type="checkbox" id="chk_'+data.id+'"></input>'));
}else if(opts.rownumber){
$(td).addClass("rownumber");
$(td).attr("nowrap","nowrap");
$(td).css("width","20px");
tr.append(td.append('<label>' + num + '</label>'));
}else{
if (opts.align) {
$(td).css("text-align",opts.align);
}
tr.append(td.append(this.drawCell(data[opts.field],num,i,data)));
}
}
if (num % 2 == 1) tr.addClass("alt-row");
return tr; 
};
this.drawCell=function(value, row, column, object){
return this._drawCell(value, column);
};
this._drawCell=function(value, column){
if (column == 'head') {
return value;
} else {
return value;
}
};
this.pageClick=function(intPageIndex,pageSize){
this.curPage=intPageIndex;
this.pageSize=pageSize;
this.setCookie(this.cookieName(), this.curPage);
this.init();
};
this.nextPage=function(){
this.curPage = parseInt(this.curPage,10) + 1;
this.reload();
};
this.selectAll=function() {
var checkboxs = $("#"+this.tableID + " tbody .rowselect");
for(var i=0;i<checkboxs.length; i++) {
checkboxs[i].checked = true;
}
};
this.unSelectAll=function() {
var checkboxs = $("#"+this.tableID + " tbody .rowselect");
for(var i=0;i<checkboxs.length; i++) {
checkboxs[i].checked = false;
}
};
this.getSelection=function(){
var checkboxs = $("#"+this.tableID + " tbody .rowselect");
var result = [];
for(var i=0;i<checkboxs.length; i++) {
if (checkboxs[i].checked) {
var tdid = $(checkboxs[i]).parent().attr("id");
var arr = tdid.split("_");
var rownum = arr[arr.length-2];
result.push(this.data[rownum-1]);
}
}
return result;
};
this.getValue=function(row,colName){
if (row > this.data.length-1) return null;
var rowData = this.data[row];
var num = 0;
if (this.options.rownumbers) num++;
if (this.options.checkbox) num++;
if (colName) {
return rowData[byName(colName)-num];
} else {
return rowData;
}
};
this.byName=function(colName){
for (var i=0; i<this.columnNames.length; i++) {
if (colName == this.columnNames[i]) {
return i;
}
}
};
this.select=function(id){
$("#chk_"+id).attr("checked","checked");
};
this.getObject=function(id){
var obj = null;
    for (var i=0; i<this.data.length; i++) {
    if (this.data[i].id == id) {
    obj = this.data[i];
    break;
    }
    }
    if (obj == null) {
    $.message.alert("错误","无法找到对象");
    }
    return obj;
};
};
function toggleDataTableSelection(tableid,element){
var checkboxs = $("#"+tableid + " tbody .rowselect");
for(var i=0;i<checkboxs.length; i++) {
checkboxs[i].checked = element.checked;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值