您的位置:首页 > Web前端 > JQuery

4k项目基于jquery写的表格及分页的插件

2017-07-06 00:00 627 查看
/****
* 表格插件option。
* insertId:ID, 必传,需要插入的ID,可以是遮罩,或者其他DIV
* layer:[], 必传,表格的表头,以及数据取值的key值,仅支持最多2行的合并,列不限制,
* layer:[{cellName: "网元名称",cellKey: "NAME"}, {cellName: "网元名称",cellKey: [{cellName: "网元名称",cellKey: "NAME"},...]},...]
* params: {}, 必传,包含page等在内发送请求所需要的所有参数
* rqUrl: url, 必传,请求的地址
* fucBeforeRender: function, 请求数据完成时的回调,可以通过该函数将数据处理成需要的格式
* style: {}, 插件生成的DOM最外层DIV的样式,style: {"width": "100%"}
* navbar: ("simple","multi", "munual"), 顶部工具条,三选一或者不传,如果是munual,则手动配置HTML,需要与navbarHtml配合使用
* navbarHtml:string, 传入HTML字符串形式, 手动HTML要实现关闭按钮,需要在关闭按钮上添加: [data-rby='close'], 导出则添加:[data-rby='export']
* subnav/subnavHtml: ("simple","multi", "munual"),子导航,用法同navbar/navbarHtml
* toolbar/toolbarHtml: ("simple","multi", "munual") 底部工具条,用法同navbar/navbarHtml
* title:string 表格的标题,在navbar = "simple" 或者 subnav = "multi" 或者 手动配置的HTML, 都可接受title
****/
function $4kTable(option) {
this.option = option || {};
this.option.cachedParams = $.extend(true, {}, this.option.params);
//初始化
this._init();
}

$4kTable.prototype = {
constructor: $4kTable,
_init: function() {
//只初始化一次
if(this.initialized) {
return;
}

var $option = this.option;
var $tableId = $option.insertId + "_table";

var wrapStyle = "";
if($option.style && !$option.pageOnly) {
for(var i in $option.style) {
wrapStyle += i + ": " + $option.style[i] + ";";
}
}

//生成表格所需的DOM拼接字符串
var _html = "",
_navbarHtml = "",
_subnavHtml = "",
_toolbarHtml = "";
// 选择表格顶部工具条
if(!$option.pageOnly) {
_html += "<div class=table_outer id=" + $tableId.replace("#", "") + " style='" + wrapStyle + "'>";

if($option.navbar == "multi") {
_navbarHtml += '<div class="table_nav">' +
'<span class="table_nav_detail">详细信息</span>' +
'<span class="table_close" data-rby="close">+</span>' +
'</div>'
} else if($option.navbar == "simple") {
_navbarHtml += "<div class='top_ctrl'>" +
"<strong>" + (this.option.title || "") + "</strong>" +
"<span class='glyphicon glyphicon-remove pull-right close_btn' data-rby='close'></span>" +
"<span class='glyphicon glyphicon-download-alt pull-right' data-rby='export'></span>" +
"</div>"
} else if($option.navbar == "manual") {
_navbarHtml += (this.option.navbarHtml || "");
}
_html += _navbarHtml + '<div class="table_wrap">';

//表格上部分工具条
if($option.subnav == "multi") {
_subnavHtml += "<div class='table_subnav table_sub_style'>" +
"<h3>" + (this.option.title || "") + "</h3>" +
"<div class='table_tick'>" +
"<span class='float-right table_export' data-rby='export'><span class='table_export_icon'></span>" +
"<span>导出</span></span>" +
"</div>" +
"</div>"
} else if($option.subnav == "simple") {
_subnavHtml += '<div class="table_subnav">' +
'<span class="float-left table_subnav_info">当前不满足发展网元列表 <b class=table_notes title="网元当前的可放号用户总数小于目标放号数,或者放号比例小于100%,说明网元当前的放号能力不能满足用户的发展。">?</b></span>' +
'<span class="float-right table_export" data-rby="export"><span class="table_export_icon"></span><span>导出</span></span>' +
'</div>';
} else if($option.subnav == "manual") {
_subnavHtml += (this.option.subnavHtml || "");
}
_html += _subnavHtml + '<table data-rby="table" class="c_table">' +
'<thead></thead>' +
'<tbody></tbody>' +
'</table>';
}

//是否需要分页相关工具条
if($option.toolbar == "multi") {
_toolbarHtml += '<div class="table_toolbars clearfix" data-rby="toolbar">' +
'<div class="float-left table_tools_wrap">' +
'<div class="table_select_bar"><span>每页</span>' +
'<select><option>5</option><option>10</option><option>15</option></select><span>条</span>' +
'</div>' +
'<div class="table_page_wrap">' +
'<span data-rby="first" class="table_page_first"><i class="glyphicon glyphicon-step-backward "></i></span>' +
'<span data-rby="pre" class="table_page_pre"><i class="glyphicon glyphicon-backward"></i></span>' +
'<span data-rby="next" class="table_page_next"><i class="glyphicon glyphicon-forward"></i></span>' +
'<span data-rby="last" class="table_page_last"><i class="glyphicon glyphicon-step-forward"></i></span>' +
'<input type="number">' +
'<button>转至</button>'+
'</div></div>' +
'<div class="float-right table_tools_info">' +
'<span class="table_info_notes" data-rby="curPage"></span>/'+
'<span class="table_info_notes" data-rby="totalPage"></span> 页' +
' 共 <span class="table_info_notes" data-rby="totalCounts"></span> 条数据' +
'</div>' +
'</div>'
} else if($option.toolbar == "simple") {
_toolbarHtml += '<div class="tablePage center-block" data-rby="toolbar" style="margin:10px auto">' +
'<ul><li><span class="glyphicon glyphicon-fast-backward" data-rby="first"></span>' +
'<span class="glyphicon glyphicon-step-backward" data-rby="pre"></span>' +
'</li>' +
'<li>第<input type="number" class="currentPage" data-rby="curPage">页,' +
'共<span class="totalPage" data-rby="totalPage"></span>页' +
'</li>' +
'<li><span class="glyphicon glyphicon-step-forward" data-rby="next"></span>' +
'<span class="glyphicon glyphicon-fast-forward" data-rby="last"></span>' +
'</li>' +
'<li>每页显示<select class="showItem"><option selected>5</option><option>10</option><option>15</option></select>条</li>' +
'<li>,共<span class="totalItem" data-rby="totalCounts"></span>条</li>' +
'</ul></div>'
} else if($option.toolbar == "munual"){
_toolbarHtml += (this.option.toolbarHtml || "");
}

//如果已经存在组件,移除操作
if(!$option.pageOnly) {
_html += _toolbarHtml + '</div></div>';
if($($option.insertId).find($tableId).length) {
$($option.insertId).find($tableId).remove();
}
} else {
_html = _toolbarHtml;
if($($option.insertId).find("[data-rby='toolbar']").length) {
$($option.insertId).find("[data-rby='toolbar']").remove();
}
}

var self = this;
$($option.insertId).show();
$($option.insertId).append(_html);

if(!$option.pageOnly) {
var $twrap = $($tableId);
var $table = this.$table = $twrap.find("[data-rby='table']");
var $toolbar = this.$toolbar = $twrap.find("[data-rby='toolbar']");

this.$thead = $table.find("thead");
this.$tbody = $table.find("tbody");
} else {
var $toolbar = this.$toolbar = $($option.insertId).find("[data-rby='toolbar']");
}

if(!$option.pageOnly) {
//表格头部操作(关闭)
$twrap.on("click", "[data-rby='close']", function() {
$(self.option.insertId).hide();
$twrap.remove();
});

//导出操作
$twrap.on("click", "[data-rby='export']", function() {
if(self.option.exportHandle && typeof(self.option.exportHandle) == "function") {
self.option.exportHandle(self.option);
return;
}
var url = self.option.rqUrl.replace(".action", "Export.action");
var params = $.extend(true, {}, self.option.cachedParams);
params["emulateJSON"] = true;
delete params["jqGridPageStr"];
delete params["page"];
delete params["rows"];
$(".ajaxLoading").show();
$.post(url, params, function(res) {
$(".ajaxLoading").hide();
download_user_defined_file(res.filePath);
});
});

//添加表格头部信息,初始化的时候传入
if(this.option.layer) {
var theadHtml = this.createTableHeadHtml();
this.$thead.append(theadHtml);
}
}

//表格底部工具栏操作(每页显示条数, 分页控制, 页面选择, 行,页数显示)
var $scounts = this.$scounts = $toolbar.find("select");
var $first = this.$first = $toolbar.find("[data-rby='first']");
var $pre = this.$pre = $toolbar.find("[data-rby='pre']");
var $next = this.$next = $toolbar.find("[data-rby='next']");
var $last = this.$last = $toolbar.find("[data-rby='last']");
var $spage = $toolbar.find("button");
var $inputPage = this.$inputPage = $toolbar.find("input");

$scounts.on("change", function() {
self.option.rows = $(this)[0].value;
self.option.current = 1;
self.refresh();
});

$first.on("click", function() {
if(self.option.current == 1) {
return;
}
self.option.current = 1;
self.refresh();
});

$pre.on("click", function() {
if(self.option.current <= 1) {
return;
}
self.option.current--;
self.refresh();
});

$next.on("click", function() {
if(self.option.current >= self.option.total) {
return;
}
self.option.current++;
self.refresh();
});

$last.on("click", function() {
if(self.option.current >= self.option.total) {
return;
}
self.option.current = self.option.total;
self.refresh();
});

$spage.on("click", function() {
$pageAsset(self);
self.refresh();
});

$inputPage.on("keyup", function(e) {
var format = $(this).val().trim().replace(/\.|\+|\-/g, "");
self.$inputPage[0].value = format;
if(e.keyCode === 13) {
$pageAsset(self);
self.refresh();
}
});

function $pageAsset(self) {
var inputs = self.$inputPage.val().trim();
if(typeof(inputs - 0) == "number" && !isNaN(inputs - 0)) {
if(inputs < self.option.total && inputs > 1) {
self.option.current = inputs;
}
if(inputs >= self.option.total) {
self.option.current = self.option.total;
}
//空值,或者负数,或者undefined,null
if(inputs <= 1) {
self.option.current = 1;
}
} else {
return;
}
}

if(this.$thead) {
this.$thead.find("th").on("click", "i", function() {
if($(this).hasClass("disabled")) return;
var order;
var index = $(this).index();
if(index === 0) {
order = "asc";
} else if(index === 1) {
order = "desc";
}
self.option.sidx = $(this).parent().parent().index();
self.option.sord = order;
self.refresh();
});
}

this.refresh();
this.initialized = true;//完成初始化
},
//生成表格头部字符串
createTableHeadHtml: function(layer) {
this.tbodyKey = [];
var theadHtml = "", headRows1 = "", headRows2 = "", $headCell = layer || this.option.layer;
if($headCell) {
//检查表格是否有单元格需要合并
var needsMergeCell = $headCell.every(function(item, index) {
return typeof(item.cellKey) == "string";
});

if(needsMergeCell) {
for(var k = 0; k < $headCell.length; k++) {
//判断是否需要排序,只支持单行,没有表格合并的类型。
if(this.option.order && $headCell[k].orderString) {
headRows1 += "<th style='height:" + ($headCell[k].height || 30) + "px;white-space:nowrap'>" + $headCell[k].cellName +
"<span class='orderWrap'><i class='icon-caret-up'></i><i class='icon-caret-down'></i></span>" + "</th>";
} else {
headRows1 += "<th style='height:" + ($headCell[k].height || 30) + "px'>" + $headCell[k].cellName + "</th>";
}
this.tbodyKey.push($headCell[k].cellKey);
}
} else {
for(var k = 0; k < $headCell.length; k++) {
if(typeof($headCell[k].cellKey) == "string") {
headRows1 += "<th rowspan='2'" +  " style=height:" + ($headCell[k].height || 30) + "px>" + $headCell[k].cellName + "</th>";
this.tbodyKey.push($headCell[k].cellKey);
}
if(typeof($headCell[k].cellKey) == "object") {
headRows1 += "'<th colspan=" + $headCell[k].cellKey.length + " style=height:" + ($headCell[k].height || 30) + "px>" + $headCell[k].cellName + "</th>";
for(var i = 0; i < $headCell[k].cellKey.length; i++) {
headRows2 += "<th style=height:" + ($headCell[k].height || 30) + "px>" + $headCell[k].cellKey[i].cellName + "</th>";
this.tbodyKey.push($headCell[k].cellKey[i].cellKey);
}
}
}
}
theadHtml += "<tr>" + headRows1 + "</tr>" + "<tr>" + headRows2 + "</tr>";
}
return theadHtml;
},

refresh: function() {
var _pages = {};
var _params = this.option.cachedParams;

_pages["page"] = this.option.current || this.option.params.page;
_pages["rows"] = this.option.rows || this.$scounts[0].value || this.option.params.rows;

_params["page"] = this.option.current || this.option.params.page;
_params["rows"] = this.option.rows || this.$scounts[0].value || this.option.params.rows;
//在order与所需排序参数均齐全的情况下才添加排序参数
if(this.option.order) {
if(this.option.sidx) { // && this.option.sidx !== 0, 目前需求没有首列排序,暂时不判断
_pages["sidx"] = this.option.layer[this.option.sidx].orderString;
}
if(this.option.sord) {
_pages["sord"] = this.option.sord;
}
}

_params["jqGridPageStr"] = JSON.stringify(_pages);
_params["emulateJSON"] = true;
this.ajaxData(_params);
},
ajaxData: function(params) {
var self = this;
$(".ajaxLoading").show();
$.ajax({
url: this.option.rqUrl,
type: "POST",
data: params,
success: function(response) {
$(".ajaxLoading").hide();
var res;
//处理数据为需要的格式,先返回给外界处理,处理完成后再返回来插件内。
if(typeof(self.option.fucBeforeRender) == "function") {
res = self.option.fucBeforeRender(response, self);
} else if(response && response.results) {
res = response;
}
self.render(res);
},
error: function(response) {
$(".ajaxLoading").hide();
$4kDialogNotes();
}
});
},
render: function(res) {
if(!res) return;
var orderIndex, shouldActivedCell;

this.$inputPage[0].value = this.option.current = res.page;
this.option.records = res.records;
this.option.total = res.total;
this.option.rows = res.rows;
this.$toolbar.find("[data-rby='curPage']").text(res.page);
this.$toolbar.find("[data-rby='totalPage']").text(res.total);
this.$toolbar.find("[data-rby='totalCounts']").text(res.records);

if(this.option.current <= 1) {
this.$first.addClass("disabled");
this.$pre.addClass("disabled");
} else {
if(this.$first.hasClass("disabled")) {
this.$first.removeClass("disabled");
}
if(this.$pre.hasClass("disabled")) {
this.$pre.removeClass("disabled");
}
}
if(this.option.current >= this.option.total) {
this.$last.addClass("disabled");
this.$next.addClass("disabled");
} else {
if(this.$last.hasClass("disabled")) {
this.$last.removeClass("disabled");
}
if(this.$next.hasClass("disabled")) {
this.$next.removeClass("disabled");
}
}

if(!this.initTableHead && !this.option.layer && res.$4kLayer) {
this.$thead.append(this.createTableHeadHtml(res.$4kLayer));
this.initTableHead = true;
}

if(!this.option.pageOnly) {
var tdList = res.results;
var newTr = "";
for(var i = 0, len = tdList.length; i < len; i++) {
newTr += this.rendAsset(tdList[i]);
}
this.$tbody.empty().append(newTr);
}
//判断点击的是哪个排序,将该排序按钮置为相应状态 //同样的, 无首列排序,暂时不判断sidx为0的情况
if(this.option.sidx && this.option.sord) {
this.$thead.find("i").removeClass("disabled");
shouldActivedCell = this.$thead.find("th").eq(this.option.sidx);
if(this.option.sord == "asc") {
shouldActivedCell.find("i").eq(0).addClass("disabled");
}
if(this.option.sord == "desc") {
shouldActivedCell.find("i").eq(1).addClass("disabled");
}
}
},
rendAsset: function(obj) {
var pref = "<td>", arts = "</td>", tds = "<tr>", rate;
if(typeof(obj) !== "object") return;
var tempData;
for(var i = 0; i < this.tbodyKey.length; i++) {
tempData = obj[this.tbodyKey[i]];
if(obj[this.tbodyKey[i]]) {
tds += pref + tempData + arts;
} else {
if(tempData === "0" || tempData === 0) {
tds += pref + tempData + arts;
} else {
tds += pref + "-" + arts;
}
}

}
tds += "</tr>";
return tds;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: