/** @Name:layui.table 表格操作 @Author:贤心 @License:MIT */ layui.define(['laytpl', 'laypage', 'layer', 'form','laydate','vciWebRefer','tree'], function(exports){ "use strict"; var $ = layui.$ ,laytpl = layui.laytpl ,laypage = layui.laypage ,layer = layui.layer ,form = layui.form ,hint = layui.hint() ,device = layui.device(), laydate = layui.laydate //外部接口 ,table = { selectMode:{//表格选择模式 single:'single', muti:'muti' } ,config: { checkName: 'LAY_CHECKED' //是否选中状态的字段名 ,indexName: 'LAY_TABLE_INDEX', //下标索引名 remoteSort:true,//weidy@2018-03-05 是否使用后台来排序 checkOnSelect:true,//weidy@2018-05-17 单选行的时候自动勾选 selectMode:'single'//weidy@2018-05-17 数据单选还是多选,主要在checkOnSelect=true的时候判断是否清除其他行的复选框 } //全局配置项 ,cache: {} //数据缓存 ,index: layui.table ? (layui.table.index + 10000) : 0 //设置全局项 ,set: function(options){ var that = this; that.config = $.extend({}, that.config, options); return that; } //事件监听 ,on: function(events, callback){ return layui.onevent.call(this, MOD_NAME, events, callback); } } //操作当前实例 ,thisTable = function(){ var that = this ,options = that.config ,id = options.id; id && (thisTable.config[id] = options); return { reload: function(options){ that.reload.call(that, options); } ,config: options } } //字符常量 ,MOD_NAME = 'table', ELEM = '.layui-table', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled', NONE = 'layui-none' ,ELEM_BOX='.layui-table-box' , ELEM_TOTAL='.layui-table-total',ELEM_VIEW = 'layui-table-view', ELEM_HEADER = '.layui-table-header', ELEM_BODY = '.layui-table-body', ELEM_MAIN = '.layui-table-main', ELEM_FIXED = '.layui-table-fixed', ELEM_FIXL = '.layui-table-fixed-l', ELEM_FIXR = '.layui-table-fixed-r', ELEM_TOOL = '.layui-table-tool',ELEM_TOOLS = '.layui-table-tool-self', ELEM_PAGE = '.layui-table-page', ELEM_SORT = '.layui-table-sort', ELEM_EDIT = 'layui-table-edit', ELEM_HOVER = 'layui-table-hover' //thead区域模板 ,TPL_HEADER = function(options){ var rowCols = '{{#if(item2.colspan){}} colspan="{{item2.colspan}}"{{#} if(item2.rowspan){}} rowspan="{{item2.rowspan}}"{{#}}}'; options = options || {}; return ['' ,'' ,'{{# layui.each(d.data.cols, function(i1, item1){ }}' ,'' ,'{{# layui.each(item1, function(i2, item2){ }}' ,'{{# if(item2.fixed && item2.fixed !== "right"){ left = true; } }}' ,'{{# if(item2.fixed === "right"){ right = true; } }}' ,function(){ if(options.fixed && options.fixed !== 'right'){ return '{{# if(item2.fixed && item2.fixed !== "right"){ }}'; } if(options.fixed === 'right'){ return '{{# if(item2.fixed === "right"){ }}'; } return ''; }() ,'' ,(options.fixed ? '{{# }; }}' : '') ,'{{# }); }}' ,'' ,'{{# }); }}' ,'' ,'
' ,'
'//weidy@2018-03-15 增加标题对齐参数 ,'{{# if(item2.type === "checkbox"){ }}' //复选框 ,'' ,'{{# } else { }}' ,'{{item2.title||""}}' ,'{{# if(!(item2.colspan > 1) && item2.sort){ }}' ,'' ,'{{# } }}' ,'{{# } }}' ,'
' ,'
'].join(''); } //tbody区域模板 ,TPL_BODY = ['' ,'' ,'
'].join('') //主模板 ,TPL_MAIN = ['
' /* ,'{{# if(d.data.toolbar){ }}' ,'
' ,'{{# } }}'*/ ,'
' ,'
' ,'{{# var left, right; }}' ,'
' ,TPL_HEADER() ,'
' ,'
' ,TPL_BODY ,'
' ,'{{# if(left){ }}' ,'
' ,'
' ,TPL_HEADER({fixed: true}) ,'
' ,'
' ,TPL_BODY ,'
' ,'
' ,'{{# }; }}' ,'{{# if(right){ }}' ,'
' ,'
' ,TPL_HEADER({fixed: 'right'}) ,'
' ,'
' ,'
' ,TPL_BODY ,'
' ,'
' ,'{{# }; }}' ,'
' ,'{{# if(d.data.totalRow)}}' ,'
' ,TPL_BODY ,'
' ,'{{# if(d.data.page){ }}' ,'
' ,'
' ,'
' ,'
' ,'{{# } }}' ,'' ,'
'].join('') ,_WIN = $(window) ,_DOC = $(document) //构造器 ,Class = function(options){ var that = this; that.index = ++table.index; that.config = $.extend({}, that.config, table.config, options); that.render(); }; //默认配置 Class.prototype.config = { limit: 10 //每页显示的数量 ,loading: true //请求数据时,是否显示loading ,cellMinWidth: 60 //所有单元格默认最小宽度 ,defaultToolbar:["filter","exports","print"] ,text: { none: '无数据' } }; //表格渲染 Class.prototype.render = function(){ var that = this ,options = that.config; options.elem = $(options.elem); options.where = options.where || {}; options.id = options.id || options.elem.attr('id'); //请求参数的自定义格式 options.request = $.extend({ pageName: 'page' ,limitName: 'limit', orderName:'order',//weidy@2018-03-05使用排序的的类型, asc ,desc sortName:'sort',//排序的字段, }, options.request) //响应数据的自定义格式 options.response = $.extend({ statusName: 'code' ,statusCode: 200//weidy@2020/2/24 修改正确的状态码,以前0 ,msgName: 'msg' ,dataName: 'data' ,countName: 'total'//weidy@2018-03-05修改默认的属性,原为count }, options.response); //如果 page 传入 laypage 对象 if(typeof options.page === 'object'){ options.limit = options.page.limit || options.limit; options.limits = options.page.limits || options.limits; that.page = options.page.curr = options.page.curr || 1; delete options.page.elem; delete options.page.jump; } if(!options.elem[0]) return that; that.setArea(); //动态分配列宽高 //开始插入替代元素 var othis = options.elem ,hasRender = othis.next('.' + ELEM_VIEW) //主容器 ,reElem = that.elem = $(laytpl(TPL_MAIN).render({ VIEW_CLASS: ELEM_VIEW ,data: options ,index: that.index //索引 })); options.index = that.index; //生成替代元素 hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender othis.after(reElem); //各级容器 that.layHeader = reElem.find(ELEM_HEADER); that.layMain = reElem.find(ELEM_MAIN); that.layBody = reElem.find(ELEM_BODY); that.layFixed = reElem.find(ELEM_FIXED); that.layFixLeft = reElem.find(ELEM_FIXL); that.layFixRight = reElem.find(ELEM_FIXR); that.layTool = reElem.find(ELEM_TOOL); that.layTools = reElem.find(ELEM_TOOLS); that.layPage = reElem.find(ELEM_PAGE);//ELEM_TOTAL that.layTotal = reElem.find(ELEM_TOTAL); that.layBox = reElem.find(ELEM_BOX); that.renderToolbar(); that.layTool.html( laytpl($(options.toolbar).html()||'').render(options) ); if(options.height) that.fullSize(); //设置body区域高度 //如果多级表头,则填补表头高度 if(options.cols.length > 1){ var th = that.layFixed.find(ELEM_HEADER).find('th'); th.height(that.layHeader.height() - 1 - parseFloat(th.css('padding-top')) - parseFloat(th.css('padding-bottom'))); } //请求数据 that.pullData(that.page); that.events(); }; //2.4 工具栏 Class.prototype.renderToolbar = function(){ var that = this,options = that.config ,inline =['
' ,'
' ,'
' ].join("") ,temp = that.layTools.find(".layui-table-tool-self"); if(true===options.toolbar)temp.html(inline); else{ that.layTools.remove(); } var r = { filter:{ title:"筛选列", layEvent:"LAYTABLE_COLS", icon:"layui-icon-search", text:"筛选列" }, exports:{ title:"导出", layEvent:"LAYTABLE_EXPORT", icon:"layui-icon-share", text:"导出" }, print:{ title:"打印", layEvent:"LAYTABLE_PRINT", icon:"layui-icon-upload", text:"打印" } },d = [] "object" == typeof options.defaultToolbar && layui.each(options.defaultToolbar,function(that,t){ var i = r[t]; i && d.push('
') }),that.layTools.html(d.join("")); }; // // Class.prototype.setParentCol = function(e,t){ var that = this,options = that.config, targetDom = that.layHeader.find('th[data-key="'+options.index+"-"+t+'"]') ,n = parseInt(targetDom.attr("colspan"))||0; if(targetDom[0]){ var o = t.split("-"), r = options.col[o[0]][o[1]]; e ? n--:n++,targetDom.attr("colspan",n),targetDom[n<1?"addClass":"removeClass"](HIDE), r.colspan = n, r.hide = n < 1; var parentKey = targetDom.data("parentkey"); parentKey && that.setPatentCol(e,d) } }; //根据列类型,定制化参数 Class.prototype.initOpts = function(item){ var that = this, options = that.config ,initWidth = { checkbox: 48 ,space: 15 ,numbers: 40 }; //让 type 参数兼容旧版本 if(item.checkbox) item.type = "checkbox"; if(item.space) item.type = "space"; if(!item.type) item.type = "normal"; if(item.type !== "normal"){ item.unresize = true; item.width = item.width || initWidth[item.type]; } }; //动态分配列宽高 Class.prototype.setArea = function(){ var that = this, options = that.config ,colNums = 0 //列个数 ,autoColNums = 0 //自动列宽的列个数 ,autoWidth = 0 //自动列分配的宽度 ,countWidth = 0 //所有列总宽度和 ,cntrWidth = options.width || function(){ //获取容器宽度 //如果父元素宽度为0(一般为隐藏元素),则继续查找上层元素,直到找到真实宽度为止 var getWidth = function(parent){ var width, isNone; parent = parent || options.elem.parent() width = parent.width(); try { isNone = parent.css('display') === 'none'; } catch(e){} if(parent[0] && (!width || isNone)) return getWidth(parent.parent()); return width; }; return getWidth(); }(); //统计列个数 that.eachCols(function(){ colNums++; }); //减去边框差 cntrWidth = cntrWidth - function(){ return (options.skin === 'line' || options.skin === 'nob') ? 2 : colNums + 1; }(); //遍历所有列 layui.each(options.cols, function(i1, item1){ layui.each(item1, function(i2, item2){ var width; if(!item2){ item1.splice(i2, 1); return; } that.initOpts(item2); width = item2.width || 0; if(item2.colspan > 1) return; if(/\d+%$/.test(width)){ item2.width = width = Math.floor((parseFloat(width) / 100) * cntrWidth); } else if(!width){ //列宽未填写 item2.width = width = 0; autoColNums++; } countWidth = countWidth + width; }); }); that.autoColNums = autoColNums; //记录自动列数 //如果未填充满,则将剩余宽度平分。否则,给未设定宽度的列赋值一个默认宽 (cntrWidth > countWidth && autoColNums) && ( autoWidth = (cntrWidth - countWidth) / autoColNums ); layui.each(options.cols, function(i1, item1){ layui.each(item1, function(i2, item2){ var minWidth = item2.minWidth || options.cellMinWidth; if(item2.colspan > 1) return; if(item2.width === 0){ item2.width = Math.floor(autoWidth >= minWidth ? autoWidth : minWidth); //不能低于设定的最小宽度 } }); }); //高度铺满:full-差距值 if(options.height && /^full-\d+$/.test(options.height)){ that.fullHeightGap = options.height.split('-')[1]; options.height = _WIN.height() - that.fullHeightGap; } }; //隐藏列之后自动定宽 ---带完善 暂时用不到 Class.prototype.setColsWidth = function(){ var that = this, options = that.config, width = that.setInit("width"),i = 0,l = 0,a = 0,n = 0; that.eachCols(function(e,t){ t.hide || i ++ });width = width - function(){ return "line" === options.skin || "nob" === options.skin ? 2 : i + 1 }() - that.getScrollWidth(that.layMain[0]) - 1; var r = function(e){ layui.each(that.cols,function(i,r){ layui.each(r,function(i,d){ var c = 0,s = d.minWidth || options.cellMinWidth; return d ? void(d.colGroup || d.hide || (e ? l && l < s && (a--, c = s) : (c = d.width || 0,/\d+%$/.test(c) ? (c = Math.floor(parseFloat(c) / 100 * width),c < s && (c = s)) : c || (d.width = c = 0 , a++)), d.hide && (c = 0),n +=c)) : void r.splice(i,1) }) }),width > n && a && (l = (width - n) / a) }; r(),r(!0),that.autoColNums = a,that.eachCols(function(i,a){ var n = a.minWidth || options.cellMinWidth; a.colGroup || a.hide || (0 === a.width ? that.getCssRule(options.index + "-" + a.key,function(e){ e.style.width = Math.floor(l>=n? l:n) + "px" }) : /\d+%$/.test(a.width) && that.getCssRule(options.index + "-" + a.key,function(e){ e.style.width = Math.floor(parseFloat(a.width)/100 * width)+ "px" })) }); var d = that.layMain.width() - that.getScrollWidth(that.layMain[0]) - that.layMain.children("table").outerWidth(); if(that.autoColNums && d >= -i && d<= i){ var c = function(t){ var i; return t = t || that.layHeader.eq(0).find("thead th:last-child"),i = t.data("field"),!i && t.prev()[0] ? c(t.prev()) : t },s = c(),u = s.data("key"); that.getCssRule(u,function(t){ var i = t.style.width || s.outerWidth(); t.style.width = parseFloat(i) + d + "px",that.layMain.height() - that.layMain.prop("clientHeight") > 0 && (t.style.width = parseFloat(t.style.width) - 1 + "px") }) } //that.loading(!0) }; //待完善 Class.prototype.setInit = function(e){ var that = this,options = that.config; return options.clientWidth = options.width || function(){ var e = function(t){ var a,l; t = t || options.elem.parent(),a = t.width(); try{ l = "none" === t.css("display") }catch(n){} return !t[0] || a && !l ? a : e(t.parent()) };return e() }(),"width" === e ? options.clientWidth : void layui.each(options.cols,function(e,a){ layui.each(a,function(l,n){ if(!n)return void a.splice(l,i); if(n.key = e + "-" + l , n.hide = n.hide || !1 , n.colGroup || n.colspan > 1){ var o = 0; layui.each(options.cols[e+1],function(t,i){ i.HAS_PARENT || o >1 && o == n.colspan || (i.HAS_PARENT = !0 , i.parentKey = e + "-" +l,o +=parseInt(i.colspan > 1 ? i.colspan :1)) }), n.colGroup = !0 } that.initOpts(n) }) }) }; // Class.prototype.resize = function(){ var that = this; that.fullSize();that.scrollPatch();/*that.setColsWidth();-------待完善*/ }; //表格重载 Class.prototype.reload = function(options){ var that = this; if(that.config.data && that.config.data.constructor === Array) delete that.config.data; that.config = $.extend({}, that.config, options); that.render(); }; //页码 Class.prototype.page = 1; //获得数据 Class.prototype.pullData = function(curr, loadIndex){ var that = this ,options = that.config ,request = options.request ,response = options.response ,sort = function(){ if(typeof options.initSort === 'object'){ that.sort((options.initSort.sortField||options.initSort.field), options.initSort.type); } }; that.startTime = new Date().getTime(); //渲染开始时间 if(options.url){ //Ajax请求 var params = {}; if(options.page){ params[request.pageName] = curr; params[request.limitName] = options.limit; }else{ params[request.pageName] = 1; params[request.limitName] = -1; } if(options.remoteSort && that.sortKey){ params[request.orderName] =that.sortKey.sort;//方法 params[request.sortName] = that.sortKey.field;//字段 } var queryParams={} if(options.sourceDataParams){ //说明是扩展属性 for (var key in options.sourceDataParams) { if(key && key.constructor === Object) return; queryParams['sourceData["'+key+'"]' ] = options.sourceDataParams[key];//新的方式 } } $webUtil.ajax(options.method || 'get',options.url,$.extend(params, options.where,options.extraParams,queryParams),function (res) { if(res[response.statusName] != 0 && res[response.statusName] != response.statusCode){ that.renderForm(); that.layMain.html('
'+ (res[response.msgName] || '返回的数据状态异常') +'
'); } else { that.renderData(res, curr, res[response.countName],!options.remoteSort); if(options.remoteSort && that.sortKey){ //说明是从后台去排序的,就不需要前端排序了 }else{ sort(); } options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时(接口请求+视图渲染) } loadIndex && layer.close(loadIndex); typeof options.done === 'function' && options.done(res, curr, res[response.countName]); },function (xhr,error) { that.layMain.html('
数据接口请求异常
'); that.renderForm(); loadIndex && layer.close(loadIndex); $webUtil.showDebugMsg(error); },options.backPath); } else if(options.data && options.data.constructor === Array){ //已知数据 var res = {} ,startLimit = curr*options.limit - options.limit if(options.limit > 0){ res[response.dataName] = options.data.concat().splice(startLimit, options.limit); res[response.countName] = options.data.length; }else{ res[response.dataName] = options.data; res[response.countName] = options.data.length; } that.renderData(res, curr, options.data.length), sort(); typeof options.done === 'function' && options.done(res, curr, res[response.countName]); } }; //遍历表头 Class.prototype.eachCols = function(callback){ var cols = $.extend(true, [], this.config.cols) ,arrs = [], index = 0; //重新整理表头结构 layui.each(cols, function(i1, item1){ layui.each(item1, function(i2, item2){ //如果是组合列,则捕获对应的子列 if(item2.colspan > 1){ var childIndex = 0; index++ item2.CHILD_COLS = []; layui.each(cols[i1 + 1], function(i22, item22){ if(item22.PARENT_COL || childIndex == item2.colspan) return; item22.PARENT_COL = index; item2.CHILD_COLS.push(item22); childIndex = childIndex + (item22.colspan > 1 ? item22.colspan : 1); }); } if(item2.PARENT_COL) return; //如果是子列,则不进行追加,因为已经存储在父列中 arrs.push(item2) }); }); //重新遍历列,如果有子列,则进入递归 var eachArrs = function(obj){ layui.each(obj || arrs, function(i, item){ if(item.CHILD_COLS) return eachArrs(item.CHILD_COLS); callback(i, item); }); }; eachArrs(); }; //数据渲染 Class.prototype.renderData = function(res, curr, count, sort){ var that = this ,options = that.config ,data = res[options.response.dataName] || [] ,trs = [] ,trs_fixed = [] ,trs_fixed_r = [] //渲染视图 ,render = function(){ //后续性能提升的重点 if(!sort && that.sortKey && !that.config.remoteSort){ return that.sort((that.sortKey.sortField||that.sortKey.field), that.sortKey.sort, true); } layui.each(data, function(i1, item1){ var tds = [], tds_fixed = [], tds_fixed_r = [] ,numbers = i1 + options.limit*(curr - 1) + 1; //序号 if(item1.length === 0) return; if(!sort){ item1[table.config.indexName] = i1; } that.eachCols(function(i3, item3){ var field = item3.field || i3, content = item1[field] ,cell = that.getColElem(that.layHeader, field.split(',')[0]); if(field.indexOf("_")>-1 && field.replace("_",".") in item1){//参照字段的显示值 content = item1[field.replace("_",".")]; } if(field.indexOf(".")>-1 && field.split(".")[0] in item1 && item1[field.split(".")[0]][field.split(".")[1]]){//字段是对象,获取该对象中的值 content = item1[field.split(".")[0]][field.split(".")[1]]; } if(field.indexOf(",")>-1){//一列显示多个字段,字段之间以','分格,可为字符串 content = ''; layui.each(field.split(','), function(fi,fitem){ content += item1[$.trim(fitem)] || ((fitem in item1)?'':fitem); }) } if(item3.dateFormate){ content = $webUtil.formateDateByFormate(content,item3.dateFormate); } if(content === undefined || content === null) content = ''; if(item3.colspan > 1) return; field=field.split(',')[0]; /*if(field.indexOf(".")>-1 && field.split(".")[0] in item1){//字段是对象,获取该对象中的值 field = field.replace(/\./g,'--'); }*/ //td内容 var td = ['' ,'
' + function(){ //modify by weidy@2020-06-06 去除宽度的设置,在css上已经设置了,用于修复在设置宽度后无法动态调整宽度的问题 var tplData = $.extend(true, { LAY_INDEX: numbers }, item1); //渲染复选框列视图 if(item3.type === 'checkbox'){ return ''; } else if(item3.type === 'numbers'){ //渲染序号 return numbers; }else if(item3.type === 'dateitem'){ // return "" } //that.layDateItem() //解析工具列模板 if(item3.toolbar){ return laytpl($(item3.toolbar).html()||'').render(tplData); } return item3.templet ? function(){ return typeof item3.templet === 'function' ? item3.templet(tplData,item3) : laytpl($(item3.templet).html() || String(content)).render(tplData) }() : content; }() ,'
'].join(''); tds.push(td); if(item3.fixed && item3.fixed !== 'right') tds_fixed.push(td); if(item3.fixed === 'right') tds_fixed_r.push(td); }); trs.push(''+ tds.join('') + ''); trs_fixed.push(''+ tds_fixed.join('') + ''); trs_fixed_r.push(''+ tds_fixed_r.join('') + ''); }); //if(data.length === 0) return; that.layBody.scrollTop(0); that.layMain.find('.'+ NONE).remove(); that.layMain.find('tbody').html(trs.join('')); that.layFixLeft.find('tbody').html(trs_fixed.join('')); that.layFixRight.find('tbody').html(trs_fixed_r.join('')); that.renderForm(); that.syncCheckAll(); that.haveInit ? that.scrollPatch() : setTimeout(function(){ that.scrollPatch(); }, 50); that.haveInit = true; layer.close(that.tipsIndex); }; that.key = options.id || options.index; table.cache[that.key] = data; //记录数据 //显示隐藏分页栏 that.layPage[data.length === 0 && curr == 1 ? 'addClass' : 'removeClass'](HIDE); //排序 if(sort){ return render(); } if(data.length === 0){ that.renderForm(); that.layFixed.remove(); that.layMain.find('tbody').html(''); that.layMain.find('.'+ NONE).remove(); return that.layMain.append('
'+ options.text.none +'
'); } - that.renderTotal(data)//合计 render(); //同步分页状态 if(options.page){ //有可能每页显示的个数不在列表里 var limits = options.limits || [10,30,50,100,200,500,1000]; var isInLimits = false; layui.each(limits,function(_index,limitRecord){ if(options.limit == limitRecord){ isInLimits = true; return false; } }); if(!isInLimits){ limits.push(options.limit); } options.page = $.extend({ elem: 'layui-table-page' + options.index ,count: count ,limit: options.limit ,limits: limits ,groups: 3 ,layout: ['prev', 'page', 'next', 'skip', 'count', 'limit','refresh'] ,prev: '' ,next: '' ,doRefresh:function(obj){ },jumpBefore:function(obj,first){ if(options.beforePageJump){ return options.beforePageJump(obj,first); }else{ return true; } } ,jump: function(obj, first){ if(!first){ //分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们 //而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用) that.page = obj.curr; //更新页码 options.limit = obj.limit; //更新每页条数 that.pullData(obj.curr, that.loading()); } if(options.pageJump){//weidy@2019-05-15修改,增加页面跳转的功能 options.pageJump(obj,first); } } }, options.page); options.page.count = count; //更新总条数 laypage.render(options.page); }; that.layDateItem(); }; //表格选择事件 laydate 插件 Class.prototype.layDateItem = function(data){ var that = this,options = that.config; lay(".laydate-grid-item").each(function(){ laydate.render({ elem:this, type:'datetime', change:function(){ } }) }); }; //合计 Class.prototype.renderTotal = function(e){ var that = this,options = that.config,totalNum = {}; if(options.totalRow){ layui.each(e,function(e,i){ 0 !== i.length && that.eachCols(function(e,t){ var l = t.field || e, n = i[l]; t.totalRow && (totalNum[l] = (totalNum[l] || 0) + (parseFloat(n) || 0)) }); }); var l = []; that.eachCols(function(e,t){ var field = t.field.split(',')[0].replace('.','--') || e,index = options.index, o = [' ','
' + function(){ var e = t.totalRowText || ''; return t.totalRow ? parseFloat(totalNum[field]).toFixed(2) || e : e }(),"
"].join(""); l.push(o); }),that.layTotal.find("tbody").html(""+ l.join("")+"") } }; //找到对应的列元素 Class.prototype.getColElem = function(parent, field){ var that = this ,options = that.config; return parent.eq(0).find('.laytable-cell-'+ (options.index + '-' + field) + ':eq(0)'); }; //渲染表单 Class.prototype.renderForm = function(type){ form.render(type, 'LAY-table-'+ this.index); } //勾选获取取消勾选复选框 Class.prototype.renderCheckbox = function(checkbox,checkboxDiv,checked){ form.showCheckboxCss(checkbox,checkboxDiv,checked); } //数据排序 Class.prototype.sort = function(th, type, pull, formEvent){ var that = this ,field ,res = {} ,options = that.config ,filter = options.elem.attr('lay-filter') ,data = table.cache[that.key], thisData; //字段匹配 if(typeof th === 'string'){ that.layHeader.find('th').each(function(i, item){ var othis = $(this) ,_field = othis.data('field'); if(_field === th){ th = othis; field = _field; return false; } }); } try { var field = field.split(',')[0].replace(/\./g,'--') || th.data('field').split(',')[0].replace(/\./g,'--'); //如果欲执行的排序已在状态中,则不执行渲染 if(that.sortKey && !pull){ if(field === that.sortKey.field && type === that.sortKey.sort){ return; } } var elemSort = that.layHeader.find('th .laytable-cell-'+ options.index +'-'+ field).find(ELEM_SORT); that.layHeader.find('th').find(ELEM_SORT).removeAttr('lay-sort'); //清除其它标题排序状态 elemSort.attr('lay-sort', type || null); that.layFixed.find('th') } catch(e){ return hint.error('Table modules: Did not match to field'); } //记录排序索引和类型 that.sortKey = { field: field ,sort: type }; if(that.config.remoteSort){ /** * weidy@2018-03-05 增加使用后台来进行排序 */ if(type != 'asc' && type != 'desc'){ that.sortKey = {}; } that.pullData(that.page); if(formEvent){ layui.event.call(th, MOD_NAME, 'sort('+ filter +')', { field: field ,type: type }); } return; }else{ if(type === 'asc'){ //升序 thisData = layui.sort(data, field); } else if(type === 'desc'){ //降序 thisData = layui.sort(data, field, true); } else { //清除排序 thisData = layui.sort(data, table.config.indexName); delete that.sortKey; } res[options.response.dataName] = thisData; that.renderData(res, that.page, that.count, true); if(formEvent){ layui.event.call(th, MOD_NAME, 'sort('+ filter +')', { field: field ,type: type }); } } }; //请求loading Class.prototype.loading = function(){ var that = this ,options = that.config; if(options.loading && options.url){ return layer.msg('数据请求中', { icon: 16 ,offset: [ that.elem.offset().top + that.elem.height()/2 - 35 - _WIN.scrollTop() + 'px' ,that.elem.offset().left + that.elem.width()/2 - 90 - _WIN.scrollLeft() + 'px' ] ,time: -1 ,anim: -1 ,fixed: false }); } }; //同步选中值状态 Class.prototype.setCheckData = function(index, checked){ var that = this ,options = that.config ,thisData = table.cache[that.key]; if(!thisData[index]) return; if(thisData[index].constructor === Array) return; thisData[index][options.checkName] = checked; }; //同步全选按钮状态 Class.prototype.syncCheckAll = function(){ var that = this ,options = that.config ,checkAllElem = that.layHeader.find('input[name="layTableCheckbox"]') ,syncColsCheck = function(checked){ that.eachCols(function(i, item){ if(item.type === 'checkbox'){ item[options.checkName] = checked; } }); return checked; }; if(!checkAllElem[0]) return; if(table.checkStatus(that.key).isAll){ if(!checkAllElem[0].checked){ checkAllElem.prop('checked', true); that.renderForm('checkbox'); } syncColsCheck(true); } else { if(checkAllElem[0].checked){ checkAllElem.prop('checked', false); that.renderForm('checkbox'); } syncColsCheck(false); } }; //获取cssRule Class.prototype.getCssRule = function(field, callback){ var that = this ,style = that.elem.find('style')[0] ,sheet = style.sheet || style.styleSheet || {} ,rules = sheet.cssRules || sheet.rules; layui.each(rules, function(i, item){ if(item.selectorText === ('.laytable-cell-'+ that.index +'-'+ field.split(',')[0].replace(/\./g,'--'))){ return callback(item), true; } }); }; //铺满表格主体高度 Class.prototype.fullSize = function(){ var that = this ,options = that.config ,height = options.height, bodyHeight; if(that.fullHeightGap){ height = _WIN.height() - that.fullHeightGap; if(height < 135) height = 135; that.elem.css('height', height); } //tbody区域高度 bodyHeight = parseFloat(height) - 26-1;//parseFloat(that.layHeader.height()) - 1; 有的表格获取不到layHeader.height() 但是每个表格都应该存在 所以用26代替 if(options.toolbar){ bodyHeight = bodyHeight - that.layTool.outerHeight(); } if(options.page){ bodyHeight = bodyHeight - that.layPage.outerHeight() - 1; } if(options.size === 'lg'){ bodyHeight = parseFloat(height) - 26-66; } that.layMain.css('height', bodyHeight); }; //获取滚动条宽度 Class.prototype.getScrollWidth = function(elem){ var width = 0; if(elem){ width = elem.offsetWidth - elem.clientWidth; } else { elem = document.createElement('div'); elem.style.width = '100px'; elem.style.height = '100px'; elem.style.overflowY = 'scroll'; document.body.appendChild(elem); width = elem.offsetWidth - elem.clientWidth; document.body.removeChild(elem); } return width; }; //滚动条补丁 Class.prototype.scrollPatch = function(){ var that = this ,layMainTable = that.layMain.children('table') ,scollWidth = that.layMain.width() - that.layMain.prop('clientWidth') //纵向滚动条宽度 ,scollHeight = that.layMain.height() - that.layMain.prop('clientHeight') //横向滚动条高度 ,getScrollWidth = that.getScrollWidth(that.layMain[0]) //获取主容器滚动条宽度,如果有的话 ,outWidth = layMainTable.outerWidth() - that.layMain.width(); //表格内容器的超出宽度 //如果存在自动列宽,则要保证绝对填充满,并且不能出现横向滚动条 if(that.autoColNums && outWidth < 5 && !that.scrollPatchWStatus){ var th = that.layHeader.eq(0).find('thead th:last-child') ,field = th.data('field').split(',')[0].replace(/\./g,'--'); that.getCssRule(field, function(item){ var width = item.style.width || th.outerWidth(); item.style.width = (parseFloat(width) - getScrollWidth - outWidth) + 'px'; //二次校验,如果仍然出现横向滚动条 if(that.layMain.height() - that.layMain.prop('clientHeight') > 0){ item.style.width = parseFloat(item.style.width) - 1 + 'px'; } that.scrollPatchWStatus = true; }); } if(scollWidth && scollHeight){ if(!that.elem.find('.layui-table-patch')[0]){ var patchElem = $('
'); //补丁元素 patchElem.find('div').css({ width: scollWidth }); that.layHeader.eq(0).find('thead tr').append(patchElem) } } else { that.layHeader.eq(0).find('.layui-table-patch').remove(); } //固定列区域高度 var mainHeight = that.layMain.height() ,fixHeight = mainHeight - scollHeight; that.layFixed.find(ELEM_BODY).css('height', layMainTable.height() > fixHeight ? fixHeight : 'auto'); //表格宽度小于容器宽度时,隐藏固定列 that.layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE); //操作栏 that.layFixRight.css('right', scollWidth - 1); }; //事件处理 Class.prototype.events = function(){ var that = this ,options = that.config ,_BODY = $('body') ,dict = {} ,th = that.layHeader.find('th') ,resizing ,ELEM_CELL = '.layui-table-cell' ,filter = options.elem.attr('lay-filter'); //拖拽调整宽度 th.on('mousemove', function(e){ var othis = $(this) ,oLeft = othis.offset().left ,pLeft = e.clientX - oLeft; if(othis.attr('colspan') > 1 || othis.data('unresize') || dict.resizeStart){ return; } dict.allowResize = othis.width() - pLeft <= 10; //是否处于拖拽允许区域 _BODY.css('cursor', (dict.allowResize ? 'col-resize' : '')); }).on('mouseleave', function(){ var othis = $(this); if(dict.resizeStart) return; _BODY.css('cursor', ''); }).on('mousedown', function(e){ var othis = $(this); if(dict.allowResize){ var field = othis.data('field'); e.preventDefault(); dict.resizeStart = true; //开始拖拽 dict.offset = [e.clientX, e.clientY]; //记录初始坐标 that.getCssRule(field, function(item){ var width = item.style.width || othis.outerWidth(); dict.rule = item; dict.ruleWidth = parseFloat(width); dict.minWidth = othis.data('minwidth') || options.cellMinWidth; }); } }); //拖拽中 _DOC.on('mousemove', function(e){ if(dict.resizeStart){ e.preventDefault(); if(dict.rule){ var setWidth = dict.ruleWidth + e.clientX - dict.offset[0]; if(setWidth < dict.minWidth) setWidth = dict.minWidth; dict.rule.style.width = setWidth + 'px'; layer.close(that.tipsIndex); } resizing = 1 } }).on('mouseup', function(e){ if(dict.resizeStart){ dict = {}; _BODY.css('cursor', ''); that.scrollPatch(); } if(resizing === 2){ resizing = null; } }); //排序 th.on('click', function(){ var othis = $(this) ,elemSort = othis.find(ELEM_SORT) ,nowType = elemSort.attr('lay-sort') ,type; if(!elemSort[0] || resizing === 1) return resizing = 2; if(nowType === 'asc'){ type = 'desc'; } else if(nowType === 'desc'){ type = null; } else { type = 'asc'; } that.sort(othis, type, null, true); }).find(ELEM_SORT+' .layui-edge ').on('click', function(e){ var othis = $(this) ,index = othis.index() ,field = othis.parents('th').eq(0).data('sortField')||othis.parents('th').eq(0).data('field'); layui.stope(e); if(index === 0){ that.sort(field, 'asc', null, true); } else { that.sort(field, 'desc', null, true); } }); //v2.4 工具栏事件 that.layTools.on("click","*[lay-event]",function(e){ var eventName = $(this).attr("lay-event"),othis = $(this), s = function(e,special){ var l = $(e.list), n = special ? $('') : $(''); n.html(l), options.height && n.css("max-height",options.height - (that.layTool.outerHeight() || 50)), othis.find(".layui-table-tool-panel")[0] || othis.append(n), that.renderForm(), n.on("click",function(e){ layui.stope(e); }), e.done && e.done(n,l); }; switch(layui.stope(e), $(document).trigger("table.tool.panel.remove"),layer.close(that.tipsIndex),eventName){ case "LAYTABLE_COLS": s({ list:function(){ var e = []; return that.eachCols(function(t,i){ i.field && "normal" == i.type && e.push('
  • '); }), e.join(""); }(), done:function(){ form.on("checkbox(LAY_TABLE_TOOL_COLS)",function(e){ var checked = this.checked,i = $(e.elem), key = i.data("key"),name = i.data("name"), parentkey = i.data("parentkey"); layui.each(options.cols,function(e,t){ layui.each(t,function(t,i){ if(e + "-" + t === key ){ var d = i.hide; i.hide = !checked,that.elem.find('*[data-key="'+options.index+"-" + key + '"]')[checked ?"removeClass":"addClass"](HIDE), d != i.hide && that.setParentCol(!checked,parentkey),that.resize() } }) }) }) } }); break; case "LAYTABLE_EXPORT": /*device.ie ? layer.tips("导出功能不支持IE,请用高级浏览器导出",this,{ tips:3 }):*/s({ list:function(){ return ['
  • 导出CSV文件
  • ','
  • 导出到Excel文件
  • '].join("") }(), done:function(e,i){ i.on("click",function(){ var type = $(this).data("type"),target = that; table.exportFile(options.id,null,type,target); }) } },true); break; case "LAYTABLE_PRINT": var openNew = window.open("打印窗口","_blank"), style = [""].join(""), headerHtml = $(that.layHeader.html()); headerHtml.append(that.layMain.find("table").html()),headerHtml.find("th.layui-table-patch").remove(),headerHtml.find("td[data-field='LAY_CHECKED']").remove(),headerHtml.find("th[data-field='LAY_CHECKED']").remove(),headerHtml.find(".layui-table-col-special").remove(),openNew.document.write(style + headerHtml.prop("outerHTML")),openNew.document.close(),openNew.print(),openNew.close() } layui.event.call(this,MOD_NAME,"toolbar("+ELEM_VIEW+")", $.extend({ event:eventName, config:options },{})) }); table.creatExcelIE = function(columns,rows){ var oXL ; //创建AX对象excel try{ oXL = new ActiveXObject("Excel.Application") }catch(e){ $webUtil.showMsg("请在本地安装Excel!" + "并在Internet安全设置中将‘对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本’勾选为启用"); return; } if(oXL == null){ $webUtil.showMsg("请在本地安装Excel!" + "并在Internet安全设置中将‘对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本’勾选为启用"); } //获取workbook对象 var oWB = oXL.Workbooks.Add(); //激活当前sheet var oSheet = oWB.ActiveSheet; //设置工作薄名称 oSheet.name = "导出Excel报表"; for (var i = 0; i < columns.length; i++) { oSheet.Cells(1, i + 1).value = columns[i].title; } for (var i = 0; i < rows.length; i++) { for (var j = 0; j < columns.length; j++) { if (rows[i][columns[j].field] != null) { oSheet.Cells(i + 2, j + 1).value = rows[i][columns[j].field].toString(); } else { oSheet.Cells(i + 2, j + 1).value = ""; } } } //设置excel可见属性 oXL.Visible = true; oSheet.Columns.AutoFit; } //文件导出 table.exportFile = function(e,t,i,target){ t = t || table.clearCacheKey(table.cache[e]),i = i || "csv"; var options = thisTable.config[e] || {},columns = options.cols[0],rows = table.cache[e], l = { csv : "text/csv", xls : "application/vnd.ms-excel" }[i], n = document.createElement("a"); return device.ie ? table.creatExcelIE(columns,rows)/*hint.error("IE_NOT_SUPPORT_EXPORTS")*/ : (n.href = "data:" + l +";charset=utf-8,\ufeff" + encodeURIComponent(function(){ var i = [],a = []; return layui.each(t,function(t,l){ var n = []; "object" == typeof e ? (layui.each(e,function(e,a){ 0 == t && i.push(a || "") }),layui.each(table.clearCacheKey(l),function(e,t){ n.push(t); })) : target.eachCols(function(e,a){ a.field && "normal" == a.type && !a.hide && (0 == t && i.push(a.title || ""), n.push(l[a.field])) }), a.push(n.join(",")); }), i.join(",") + "\r\n" + a.join("\r\n") }()), n.download = (options.title || "table_" + (options.index || "")) + "." + i,document.body.appendChild(n), n.click(),void document.body.removeChild(n)) }; //复选框选择 that.elem.on('click', 'input[name="layTableCheckbox"]+', function(){ var checkbox = $(this).prev() ,childs = that.layBody.find('input[name="layTableCheckbox"]') ,index = checkbox.parents('tr').eq(0).data('index') ,checked = checkbox[0].checked ,isAll = checkbox.attr('lay-filter') === 'layTableAllChoose'; //全选 if(isAll){ childs.each(function(i, item){ item.checked = checked; that.setCheckData(i, checked); }); that.syncCheckAll(); that.renderForm('checkbox'); } else { that.setCheckData(index, checked); that.syncCheckAll(); } layui.event.call(this, MOD_NAME, 'checkbox('+ filter +')', { checked: checked ,data: table.cache[that.key] ? (table.cache[that.key][index] || {}) : {} ,type: isAll ? 'all' : 'one' }); }); //行事件 that.layBody.on('mouseenter', 'tr', function(){ var othis = $(this) options =that.config ; othis.addClass(ELEM_HOVER) if(!!options.hoverCursor){ othis.find('td').css({cursor:options.hoverCursor==true?'pointer':options.hoverCursor}) } }).on('mouseleave', 'tr', function() { var othis = $(this) options = that.config; othis.removeClass(ELEM_HOVER) if (!!options.hoverCursor) { othis.find('td').css({cursor: 'default'}) } }).on('click','tr',function(e){ //weidy@2018-05-07 增加行点击事件 var othis = $(this),index = othis.index() ,dataIndex = othis.attr("data-index") ,options =that.config ;//数据所在行 var data = table.cache[that.key][dataIndex]; /*if(options.checkOnSelect && data){ var newCheckValue = !data[options.checkName]; if(options.selectMode == table.selectMode.single){ //去除其他的复选框 that.layBody.find("input[name='layTableCheckbox']").each(function(_index){ that.layBody.find('tr:eq('+ _index +')').removeClass("layui-table-click"); that.setCheckData($(this).parent().parent().parent().attr("data-index"),false); that.renderCheckbox($(this),$(this).next(),false); }); //去除其他的选中样式 that.layBody.find("tr.layui-table-click").each(function(_index){ $(this).removeClass("layui-table-click"); }); that.layBody.find('tr:eq('+ index +')').addClass("layui-table-click") }else{ that.layBody.find('tr:eq('+ index +')').toggleClass("layui-table-click") } that.setCheckData(dataIndex,newCheckValue); var checkbox = that.layBody.find('tr:eq('+ index +') input[name="layTableCheckbox"]'); that.renderCheckbox(checkbox,checkbox.next(),newCheckValue); that.syncCheckAll(); }*/ if((e.ctrlKey || e.target.className=='layui-icon' && $(e.target).parent().hasClass('layui-form-checkbox')) && data){ //点击的是checkbox框或者点击时ctrl已按下 var newCheckValue = !data[options.checkName]; that.setCheckData(dataIndex,newCheckValue); var checkbox = that.layBody.find('tr:eq('+ index +') input[name="layTableCheckbox"]'); that.renderCheckbox(checkbox,checkbox.next(),newCheckValue); that.syncCheckAll(); layui.event.call(this, MOD_NAME, 'checkbox('+ filter +')', { checked: newCheckValue ,data: data ,type: 'one' }); }else { //去除其他的选中项 that.layBody.find('tr').removeClass("layui-table-click"); that.layBody.find('tr:eq(' + index + ')').addClass("layui-table-click") } if(options.rowClick){ options.rowClick(that.key,data,newCheckValue); } layui.stope(e); }).on('dblclick','tr',function(e){ //wangting@2021-2-5 增加双击行事件 var othis = $(this),index = othis.index() ,dataIndex = othis.attr("data-index") ,options =that.config ;//数据所在行 if(options.rowDBLClick){ var data = table.cache[that.key][dataIndex]; options.rowDBLClick(that.key,data); } layui.stope(e); }); //单元格编辑 that.layBody.on('change', '.'+ELEM_EDIT, function(){ var othis = $(this) ,value = this.value ,field = othis.parent().data('field') ,index = othis.parents('tr').eq(0).data('index') ,data = table.cache[that.key][index]; //weidy@2019-05-15 增加单元格修改前的值 if(!table.editCache){ table.editCache = {}; } if(!(that.key in table.editCache) ){ table.editCache[that.key] = {}; } var editBeforeData = {}; for(var key in data){ editBeforeData[key] = data[key]; } table.editCache[that.key][index] = editBeforeData; //end weidy;暂时不直接传递到edit里,可以通过方法获取到修改前的值 if(othis.is('select')){ var text = othis.find('option:selected').text(); data[field] = text; data[$(this).attr('valueField')] = value; }else { data[field] = value; //更新缓存中的值 } $(this).parent().addClass("layui-table-edit_notsubmit"); layui.event.call(this, MOD_NAME, 'edit('+ filter +')', { value: value ,data: data ,field: field }); }).on('blur', '.'+ELEM_EDIT, function(){ var templet ,othis = $(this) ,field = othis.parent().data('field') ,index = othis.parents('tr').eq(0).data('index') ,data = table.cache[that.key][index], specialClass = othis.attr('class').split(' ')[0]; if(specialClass ==='laydate-grid-item'){//阻止laydate 点击之后remove }else{ var isRemove ; if(specialClass ==='grid-number-input'){ // var reg = new RegExp("^[0-9]+$"),value=this.value; var reg = new RegExp("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"),value=this.value; if ((value == null || value == '') || reg.test(value)){ isRemove = false; }else { layui.layer.tips("只能填写数字", othis); //$webUtil.showErrorMsg("只能填写数字"); isRemove = true; this.value = ''; } } var displayValue = this.value; if(specialClass === 'grid-select-input' || othis.is('select')){ displayValue = othis.find('option:selected').text(); } that.eachCols(function(i, item){ if(item.field == field && item.templet){ templet = item.templet; } }); othis.siblings(ELEM_CELL).html( templet ? laytpl($(templet).html() || displayValue).render(data) : displayValue ); othis.parent().data('content', displayValue); isRemove || othis.remove(); } }); //单元格事件 that.layBody.on('click', 'td', function(){ var othis = $(this) ,field = othis.data('field') ,editType = othis.data('edit') ,elemCell = othis.children(ELEM_CELL) ,editConfig=othis.attr("data-editConfig"); layer.close(that.tipsIndex); if(othis.data('off')) return; if(!editConfig){ editConfig = {}; }else{ editConfig = eval("(" + editConfig + ")"); } //显示编辑表单 if(editType){ if(editType === 'select') { //选择框 if(!editConfig.comboxKey){ $webUtil.showErrorMsg("代码有错误,编辑时为下拉框的时候,请设置comboxKey"); return false; } editConfig.valueField = editConfig.valueField?editConfig.valueField:field; var select = $(''); var content; if(othis.data('content')){ content = othis.data('content').split('')[0]; } var inputValue = elemCell.text() || content || ''; if(inputValue == undefined){ inputValue = ''; } select.val(inputValue); var displayed = othis.find('.'+ELEM_EDIT)[0]; othis.find('.'+ELEM_EDIT)[0] || othis.append(select); //加内容 if(!displayed) { layui.use('vciWebComboxStore', function () { var comboxConfig = {}; for (var key in editConfig.comboxConfig) { comboxConfig[key] = editConfig.comboxConfig[key]; } comboxConfig.url = comboxConfig.url ? comboxConfig.url : (!comboxConfig.data?'default':''); comboxConfig.callback = function (comboxKey, map) { var html = []; for (var key in map) { html.push(''); } select.html(html.join('')); }; layui.vciWebComboxStore.newCombox(editConfig.comboxKey, comboxConfig, editConfig.reload); }); } } else if(editType ==='date'){ var input = $(''); var content; if(othis.data('content')){ content = othis.data('content').split('')[0]; } var inputValue = elemCell.text() || content || ''; if(inputValue == undefined){ inputValue = ''; } input[0].value = inputValue; othis.find('.'+ELEM_EDIT)[0] || othis.append(input); lay(".laydate-grid-item").each(function(index,elem){ laydate.render({ elem:elem, change:function(value){ var date = value.split(" ")[0]; othis.find('div').html(date) }, done:function(value){ var date = value.split(" ")[0]; othis.find('div').html(date); setTimeout(function(){ othis.find("input").remove(); //var othis = $(elem) // var field = othis.parent().data('field') var index = othis.parents('tr').eq(0).data('index') , data = table.cache[that.key][index]; data[field] = value; //更新缓存中的值 layui.event.call(this, MOD_NAME, 'edit(' + filter + ')', { value: value , data: data , field: field }); },200) } }) }); setTimeout(function(){input.focus()},200); }else if(editType === 'refer'){ //说明是参照 var input = $(''); var inputValue = elemCell.text() || othis.data('content') ; if(inputValue == undefined){ inputValue = ""; } input[0].value = inputValue; othis.find('.'+ELEM_EDIT)[0] || othis.append(input); input.focus(function(){ var options = editConfig.referConfig; if(!options){ $webUtil.showErrorMsg("代码错误,在编辑的类型为参照的时候,必须有referConfig"); return false; } layui.vciWebRefer.newRefer(filter,field,input,options); layui.vciWebRefer.addChangeValueListener(filter,field,options.showField,function(thisFilter,thisName,showField,value,rawValue,selectRecords){ var index = othis.parents('tr').eq(0).data('index') , data = table.cache[that.key][index]; data[field]=rawValue; if(editConfig.fieldMap && selectRecords&&selectRecords.length>0){ //说明需要映射 for(var key in editConfig.fieldMap){ var mapFields = editConfig.fieldMap[key].split(","); var value = []; layui.each(selectRecords,function(_index,_item){ var temp ; if(mapFields.length == 1) { var mapField = mapFields[0]; if(mapField.indexOf("attribute.")>-1 ){ temp = _item['attributes'][mapField.subString("attribute.".length)]; }else { temp = _item[mapField]; } }else{ //有多个 var mutiTemp = []; layui.each(mapFields,function (_indexField,_itemField){ if(_itemField.indexOf("attribute.")>-1 ){ mutiTemp.push(_item['attributes'][_itemField.subString("attribute.".length)]); }else { mutiTemp.push(_item[_itemField]); } }); temp = mutiTemp.join(editConfig.textSep?editConfig.textSep:' '); } if (temp != null && temp != '') { value.push(temp); } }); data[key] = value.join(','); var fieldTd = othis.parent().find('td[data-field="' + key + '"]'); if(fieldTd){ fieldTd.find('div').html(data[key]); } } } othis.find('div').html(rawValue); var selectValue = { value:value, rawValue:rawValue, allValues:selectRecords }; layui.event.call(this, MOD_NAME, 'edit(' + filter + ')', { value: value , data: data , field: field ,index:index ,selectEditData:selectValue }); othis.find('.grid-refer-input').remove(); }); layui.vciWebRefer.showRefer(filter,field); }); } else { //文本框 var input; if(editType === 'number'){ input = $(''); }else{ input = $(''); } input[0].value = othis.data('content') || elemCell.text(); othis.find('.'+ELEM_EDIT)[0] || othis.append(input); input.focus(); } return; } //如果出现省略,则可查看更多 if(elemCell.find('.layui-form-switch,.layui-form-checkbox')[0]) return; //限制不出现更多(暂时) if(Math.round(elemCell.prop('scrollWidth')) > Math.round(elemCell.outerWidth())){ that.tipsIndex = layer.tips([ '
    ' ,elemCell.html() ,'
    ' ,'' ].join(''), elemCell[0], { tips: [3, ''] ,time: -1 ,anim: -1 ,maxWidth: (device.ios || device.android) ? 300 : 600 ,isOutAnim: false ,skin: 'layui-table-tips' ,success: function(layero, index){ if(event.stopPropagation){ event.stopPropagation() }else{ event.cancelBubble = true } document.onclick = function(){ layer.close(index) } /* layero.find('.layui-table-tips-c').on('click', function(){ layer.close(index); }); */ } }); } }); //工具条操作事件 that.layBody.on('click', '*[lay-event]', function(){ var othis = $(this) ,index = othis.parents('tr').eq(0).data('index') ,tr = that.layBody.find('tr[data-index="'+ index +'"]') ,ELEM_CLICK = 'layui-table-click' ,data = table.cache[that.key][index]; layui.event.call(this, MOD_NAME, 'tool('+ filter +')', { data: table.clearCacheKey(data) ,event: othis.attr('lay-event') ,tr: tr ,del: function(){ table.cache[that.key][index] = []; tr.remove(); that.scrollPatch(); } ,update: function(fields){ fields = fields || {}; layui.each(fields, function(key, value){ if(key in data){ var templet, td = tr.children('td[data-field="'+ key +'"]'); data[key] = value; that.eachCols(function(i, item2){ if(item2.field == key && item2.templet){ templet = item2.templet; } }); td.children(ELEM_CELL).html( templet ? laytpl($(templet).html() || value).render(data) : value ); td.data('content', value); } }); }, index:index //modify by weidy@2020-5-18 把行号也传递过去 }); //判断当前点击是否处理固定列中 /*if($(this).closest('.layui-table-fixed').length>0){ var prevTr=$(this).closest('.layui-table-fixed').prev('.layui-table-main').find('table tr').eq(index); prevTr.trigger('click') }*/ //tr.addClass(ELEM_CLICK).siblings('tr').removeClass(ELEM_CLICK); }); //同步滚动条 that.layMain.on('scroll', function(){ var othis = $(this) ,scrollLeft = othis.scrollLeft() ,scrollTop = othis.scrollTop(); that.layHeader.scrollLeft(scrollLeft); that.layFixed.find(ELEM_BODY).scrollTop(scrollTop); layer.close(that.tipsIndex); }); _WIN.on('resize', function(){ //自适应 that.fullSize(); that.scrollPatch(); }); _DOC.on('click',function(){ _DOC.trigger("table.remove.tool.panel") }); _DOC.on("table.remove.tool.panel",function(){ $(".layui-table-tool-panel").remove(); }); _WIN.on("resize",function(){ that.resize(); }); }; // //初始化 table.init = function(filter, settings){ settings = settings || {}; var that = this ,elemTable = filter ? $('table[lay-filter="'+ filter +'"]') : $(ELEM + '[lay-data]') ,errorTips = 'Table element property lay-data configuration item has a syntax error: '; //遍历数据表格 elemTable.each(function(){ var othis = $(this), tableData = othis.attr('lay-data'); try{ tableData = new Function('return '+ tableData)(); } catch(e){ hint.error(errorTips + tableData) } var cols = [], options = $.extend({ elem: this ,cols: [] ,data: [] ,skin: othis.attr('lay-skin') //风格 ,size: othis.attr('lay-size') //尺寸 ,even: typeof othis.attr('lay-even') === 'string' //偶数行背景 }, table.config, settings, tableData); filter && othis.hide(); //获取表头数据 othis.find('thead>tr').each(function(i){ options.cols[i] = []; $(this).children().each(function(ii){ var th = $(this), itemData = th.attr('lay-data'); try{ itemData = new Function('return '+ itemData)(); } catch(e){ return hint.error(errorTips + itemData) } var row = $.extend({ title: th.text() ,colspan: th.attr('colspan') || 0 //列单元格 ,rowspan: th.attr('rowspan') || 0 //行单元格 }, itemData); if(row.colspan < 2) cols.push(row); options.cols[i].push(row); }); }); //获取表体数据 othis.find('tbody>tr').each(function(i1){ var tr = $(this), row = {}; //如果定义了字段名 tr.children('td').each(function(i2, item2){ var td = $(this) ,field = td.data('field'); if(field){ return row[field] = td.html(); } }); //如果未定义字段名 layui.each(cols, function(i3, item3){ var td = tr.children('td').eq(i3); row[item3.field] = td.html(); }); options.data[i1] = row; }); table.render(options); }); return that; }; table.getConfig = function(id){ if(!table.settings){ table.settings = {}; } return table.settings[id]; }; table.setConfig = function(options){ if(!table.settings){ table.settings = {}; } table.settings[options.id] = options; thisTable.config[options.id] = options; }; //表格选中状态 table.checkStatus = function(id,hasIndex){ var nums = 0 ,invalidNum = 0 ,arr = [] ,data = table.cache[id] || []; //计算全选个数 layui.each(data, function(i, item){ if(item.constructor === Array){ invalidNum++; //无效数据,或已删除的 return; } if(item[table.config.checkName]){ nums++; arr.push(table.clearCacheKey(item,hasIndex)); } }); return { data: arr //选中的数据 ,isAll: data.length ? (nums === (data.length - invalidNum)) : false //是否全选 }; }; //weidy添加,自动选择某些行 table.selectRecord = function(id,selectRecords){ var that = this ,options = table.getConfig(id) ,thisData = table.cache[id]; if(!$.isArray(selectRecords)){ selectRecords = [selectRecords]; } layui.each(selectRecords, function (_index, item) { if (item.LAY_TABLE_INDEX*1>=0 || item.index*1>=0) { $(options.elem).next().find('tbody>tr[data-index="' + ((that.config.indexName in item)?item[that.config.indexName]:item.index) + '"]').each(function (i) { $(this).click(); //modify by weidy@2020-12-19,在有toolbar的时候,会有两个,所以第一个就返回 return false; }); } }); }; //weidy添加,获取当前页面的数据 table.getData = function(id){ return table.cache[id]; }; //weidy添加,获取当前页面编辑过的数据 table.getModifyData = function(id){ var data = []; var thisTableData = table.cache[id]; if(thisTableData && table.editCache && table.editCache[id]){ var thisTableBeforeData = table.editCache[id]; for(var rowIndex in thisTableBeforeData){ if(thisTableData[rowIndex]){ data.push(thisTableData[rowIndex]); } } } return data; }; //weidy添加,添加数据到列表中 table.addData = function(id,data){ var cacheData = this.getData(id); if(!data) data = []; if(!cacheData){ cacheData = []; } if(!$webUtil.isArray(data)) data = [data]; for(var i = 0 ; i < data.length ; i ++){ cacheData.push(data[i]); } this.reload(id,{ data:cacheData, modifyData:true }); }; /** * 移除数据 * id 表格的id * index,可以是行号-1,也可以是整行数据。可以是数组,也可以是单个对象 */ table.removeData = function(id,index){//移除数据 if(!$webUtil.isArray(index)) index = [index]; var data = this.getData(id); if(!data){ return false; } var newData = []; for(var i = 0 ; i < data.length ; i ++){ var isNeedDelete = false; var record = data[i]; for(var j = 0 ; j < index.length ; j ++){ var selectData = index[j]; if(!isNaN(selectData)){ //是行号的时候 if(selectData == record[table.config.indexName] ){ isNeedDelete = true; break; } }else if("oid" in selectData && "oid" in record){ if(selectData["oid"] == record["oid"] ){ isNeedDelete = true; break; } }else{ //只能全部对比所有的数据 var same = true; for(var key in selectData){ if(selectData[key] != record[key] ){ same = false; break; } } if(same){ isNeedDelete = true; break; } } } if(!isNeedDelete){ var copyData = record; delete copyData[table.config.indexName]; newData.push(copyData); } } this.reload(id,{ data:newData, modifyData:true }); }; table.changeRecord = function(id,index,record){ //修改某一行的数据 var data = this.getData(id); if(!data){ return false; } layui.each(data,function (_index,rowData) { var same = false; if(table.config.indexName in rowData && table.config.indexName in record ){ if(rowData[table.config.indexName] == record[table.config.indexName] ){ same = true; } }else if("oid" in rowData && "oid" in record){ if(rowData["oid"] == record["oid"] ){ same = true; } }else{ same = true; for(var key in rowData){ if(rowData[key] != rowData[key] ){ same = false; break; } } } if(same){ data[_index] = record; return true; } }); this.reload(id,{ data:data, modifyData:true }); }; //weidy添加,清除所有已经编辑过的数据 table.clearModifyData = function(id,rowIndexs){ if(table.editCache && table.editCache[id]){ if(rowIndexs){ //说明指定了哪些行的 var thisTableBeforeData = table.editCache[id]; if(! $webUtil.isArray(rowIndexs)){ rowIndexs = [rowIndexs]; } layui.each(rowIndexs,function(_index,_item){ delete thisTableBeforeData[rowIndexs]; }); table.editCache[id] = thisTableBeforeData; }else { table.editCache[id] = {}; } try { this.getConfig(id).elem.next().find('.layui-table-edit_notsubmit').removeClass("layui-table-edit_notsubmit"); }catch(e){ } } }; //表格重载 thisTable.config = {}; table.reload = function(id, options){ var config = thisTable.config[id]; options = options || {}; if(!config) return hint.error('The ID option was not found in the table instance'); if(options.data && options.data.constructor === Array) delete config.data; return table.render($.extend(true, {}, config, options)); }; table.getIndexColumn= function(){ return {field:table.config.indexName,type:'numbers',title:'序号',width:40}; }; table.getCheckColumn = function () { return {field:table.config.checkName,type:'checkbox',width:30}; }; //核心入口 table.render = function(options){ if(layui.util.isNull(options.id)){ if(layui.util.isNotNull(options.elem) && $(options.elem)){ options.id = $(options.elem).attr("lay-filter"); } if(layui.util.isNull(options.id)) options.id = layui.util.uuid(); } var inst = new Class(options); if(!table.settings){ table.settings = {}; } table.settings[options.id] = options; return thisTable.call(inst); }; //清除临时Key table.clearCacheKey = function(data,hasIndex){ data = $.extend({}, data); if(!hasIndex) { delete data[table.config.checkName]; delete data[table.config.indexName]; } return data; }; //自动完成渲染 table.init(); exports(MOD_NAME, table); });