From b81a9a6d95a34099ad94f2448c679bc03424856c Mon Sep 17 00:00:00 2001
From: ruciwuyu <1102059895@qq.com>
Date: Fri, 22 Dec 2017 14:13:36 +0800
Subject: [PATCH] =?UTF-8?q?=E6=9C=AC=E5=9C=B0table=E7=89=B9=E5=BC=82?=
=?UTF-8?q?=E5=8C=96?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
laymodel2
---
src/lay/modules/table.js | 2585 ++++++++++++++++++++------------------
src/layuiModel-2.js | 412 ++++++
2 files changed, 1748 insertions(+), 1249 deletions(-)
create mode 100644 src/layuiModel-2.js
diff --git a/src/lay/modules/table.js b/src/lay/modules/table.js
index 67bfdddc..37e42797 100644
--- a/src/lay/modules/table.js
+++ b/src/lay/modules/table.js
@@ -3,1273 +3,1360 @@
@Name:layui.table 表格操作
@Author:贤心
@License:MIT
-
+
*/
-
-layui.define(['laytpl', 'laypage', 'layer', 'form'], function(exports){
- "use strict";
-
- var $ = layui.$
- ,laytpl = layui.laytpl
- ,laypage = layui.laypage
- ,layer = layui.layer
- ,form = layui.form
- ,hint = layui.hint()
- ,device = layui.device()
- //外部接口
- ,table = {
- config: {
- checkName: 'LAY_CHECKED' //是否选中状态的字段名
- ,indexName: 'LAY_TABLE_INDEX' //下标索引名
- } //全局配置项
- ,cache: {} //数据缓存
- ,index: layui.table ? (layui.table.index + 10000) : 0
-
- //设置全局项
- ,set: function(options){
- var that = this;
- that.config = $.extend({}, that.config, options);
- return that;
+layui.define(['laytpl', 'laypage', 'layer', 'form'], function (exports) {
+ "use strict";
+
+ var $ = layui.$,
+ laytpl = layui.laytpl,
+ laypage = layui.laypage,
+ layer = layui.layer,
+ form = layui.form,
+ hint = layui.hint(),
+ device = layui.device()
+
+ //外部接口
+
+ ,
+ table = {
+ config: {
+ checkName: 'LAY_CHECKED' //是否选中状态的字段名
+
+ , indexName: 'LAY_TABLE_INDEX' //下标索引名
+ //全局配置项
+
+ }, cache: {} //数据缓存
+
+ , index: layui.table ? layui.table.index + 10000 : 0
+
+ //设置全局项
+
+ , set: function set(options) {
+ var that = this;
+ that.config = $.extend({}, that.config, options);
+ return that;
+ }
+
+ //事件监听
+
+ , on: function on(events, callback) {
+ return layui.onevent.call(this, MOD_NAME, events, callback);
+ }
+
+ //操作当前实例
+
+ },
+ thisTable = function thisTable() {
+ var that = this,
+ options = that.config,
+ id = options.id;
+
+ id && (thisTable.config[id] = options);
+
+ return {
+ reload: function reload(options) {
+ that.reload.call(that, options);
+ },
+ config: options
+ };
}
-
- //事件监听
- ,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_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_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"){ }}';
+
+ //字符常量
+
+ ,
+ MOD_NAME = 'table',
+ ELEM = '.layui-table',
+ THIS = 'layui-this',
+ SHOW = 'layui-show',
+ HIDE = 'layui-hide',
+ DISABLED = 'layui-disabled',
+ NONE = 'layui-none',
+ 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_PAGE = '.layui-table-page',
+ ELEM_SORT = '.layui-table-sort',
+ ELEM_EDIT = 'layui-table-edit',
+ ELEM_HOVER = 'layui-table-hover'
+
+ //thead区域模板
+
+ ,
+ TPL_HEADER = function TPL_HEADER(options) {
+ var rowCols = '{{#if(item2.colspan){}} colspan="{{item2.colspan}}"{{#} if(item2.rowspan){}} rowspan="{{item2.rowspan}}"{{#}}}';
+
+ options = options || {};
+ return ['', '', '{{# layui.each(d.data.showCols, 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"){ }}';
+ if (options.fixed === 'right') {
+ return '{{# if(item2.fixed === "right"){ }}';
}
return '';
- }()
- ,''
- ,' '
- ,'{{# if(item2.type === "checkbox"){ }}' //复选框
- ,''
- ,'{{# } else { }}'
- ,'{{item2.title||""}}'
- ,'{{# if(!(item2.colspan > 1) && item2.sort){ }}'
- ,''
- ,'{{# } }}'
- ,'{{# } }}'
- ,' '
- ,' | '
- ,(options.fixed ? '{{# }; }}' : '')
- ,'{{# }); }}'
- ,'
'
- ,'{{# }); }}'
- ,''
- ,'
'].join('');
- }
-
- //tbody区域模板
- ,TPL_BODY = [''].join('')
-
- //主模板
- ,TPL_MAIN = [''].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 //所有单元格默认最小宽度
- };
-
- //表格渲染
- 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'
- }, options.request)
-
- //响应数据的自定义格式
- options.response = $.extend({
- statusName: 'code'
- ,statusCode: 0
- ,msgName: 'msg'
- ,dataName: 'data'
- ,countName: '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.layPage = reElem.find(ELEM_PAGE);
-
- 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();
- };
-
- //根据列类型,定制化参数
- 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.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.field, options.initSort.type);
- }
- };
-
- that.startTime = new Date().getTime(); //渲染开始时间
-
- if(options.url){ //Ajax请求
- var params = {};
- params[request.pageName] = curr;
- params[request.limitName] = options.limit;
-
- $.ajax({
- type: options.method || 'get'
- ,url: options.url
- ,data: $.extend(params, options.where)
- ,dataType: 'json'
- ,success: function(res){
- if(res[response.statusName] != response.statusCode){
- that.renderForm();
- return that.layMain.html(''+ (res[response.msgName] || '返回的数据状态异常') +'
');
- }
- that.renderData(res, curr, res[response.countName]), sort();
- options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时(接口请求+视图渲染)
- loadIndex && layer.close(loadIndex);
- typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
- }
- ,error: function(e, m){
- that.layMain.html('数据接口请求异常
');
- that.renderForm();
- loadIndex && layer.close(loadIndex);
- }
- });
- } else if(options.data && options.data.constructor === Array){ //已知数据
- var res = {}
- ,startLimit = curr*options.limit - options.limit
-
- res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
- 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){
- return that.sort(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);
-
- if(content === undefined || content === null) content = '';
- if(item3.colspan > 1) return;
-
- //td内容
- var td = [''
- ,' ' + function(){
- var tplData = $.extend(true, {
- LAY_INDEX: numbers
- }, item1);
-
- //渲染复选框列视图
- if(item3.type === 'checkbox'){
- return '';
- } else if(item3.type === 'numbers'){ //渲染序号
- return numbers;
- }
-
- //解析工具列模板
- if(item3.toolbar){
- return laytpl($(item3.toolbar).html()||'').render(tplData);
- }
-
- return item3.templet ? 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; //记录数据
-
- //排序
- 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('无数据
');
- }
-
- render();
-
- //同步分页状态
- if(options.page){
- options.page = $.extend({
- elem: 'layui-table-page' + options.index
- ,count: count
- ,limit: options.limit
- ,limits: options.limits || [10,20,30,40,50,60,70,80,90]
- ,groups: 3
- ,layout: ['prev', 'page', 'next', 'skip', 'count', 'limit']
- ,prev: ''
- ,next: ''
- ,jump: function(obj, first){
- if(!first){
- //分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们
- //而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用)
- that.page = obj.curr; //更新页码
- options.limit = obj.limit; //更新每页条数
-
- that.pullData(obj.curr, that.loading());
- }
- }
- }, options.page);
- options.page.count = count; //更新总条数
- laypage.render(options.page);
- }
- };
-
- //找到对应的列元素
- 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.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;
- }
- });
+ }(), '', ' ', '{{# if(item2.type === "checkbox"){ }}' //复选框
+ , '', '{{# } else { }}', '{{item2.title||""}}', '{{# if(!(item2.colspan > 1) && item2.sort){ }}', '', '{{# } }}', '{{# } }}', ' ', ' | ', options.fixed ? '{{# }; }}' : '', '{{# }); }}', '', '{{# }); }}', '', '
'].join('');
}
- try {
- var field = field || th.data('field');
-
- //如果欲执行的排序已在状态中,则不执行渲染
- 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
+ //tbody区域模板
+
+ ,
+ TPL_BODY = [''].join('')
+
+ //主模板
+
+ ,
+ TPL_MAIN = [''].join(''),
+ _WIN = $(window),
+ _DOC = $(document)
+
+ //构造器
+ ,
+ Class = function Class(options) {
+ var that = this;
+ that.index = ++table.index;
+ that.config = $.extend({}, that.config, table.config, options);
+ that.render();
};
- 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;
+ //默认配置
+ Class.prototype.config = {
+ limit: 10 //每页显示的数量
+
+ , loading: true //请求数据时,是否显示loading
+
+ , cellMinWidth: 60 //所有单元格默认最小宽度
};
-
- 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)){
- 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);
- }
+ //表格渲染
+ Class.prototype.render = function () {
+ var that = this,
+ options = that.config,
+ showCols = [],
+ hideCols = []
+ ;
+ options.elem = $(options.elem);
+ options.where = options.where || {};
+ options.id = options.id || options.elem.attr('id');
+ //请求参数的自定义格式
+ options.request = $.extend({
+ pageName: 'curr',
+ limitName: 'pageSize'
+ }, options.request);
- //tbody区域高度
- bodyHeight = parseFloat(height) - parseFloat(that.layHeader.height()) - 1;
- if(options.toolbar){
- bodyHeight = bodyHeight - that.layTool.outerHeight();
- }
- if(options.page){
- bodyHeight = bodyHeight - that.layPage.outerHeight() - 1;
- }
- 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';
+ //响应数据的自定义格式
+ options.response = $.extend({
+ statusName: 'code',
+ statusCode: 1,
+ msgName: 'msg',
+ dataName: 'object',
+ countName: 'page',
+ pageRecords: 'totalRecords'
+ }, options.response);
- 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');
- 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';
+ //如果 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;
}
- 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);
- };
+ if (!options.elem[0]) return that;
- //事件处理
- 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('field')
- layui.stope(e);
- if(index === 0){
- that.sort(field, 'asc', null, true);
- } else {
- that.sort(field, 'desc', null, true);
- }
- });
-
- //复选框选择
- 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)
- ,index = othis.index();
- that.layBody.find('tr:eq('+ index +')').addClass(ELEM_HOVER)
- }).on('mouseleave', 'tr', function(){
- var othis = $(this)
- ,index = othis.index();
- that.layBody.find('tr:eq('+ index +')').removeClass(ELEM_HOVER)
- });
-
- //单元格编辑
- 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];
-
- data[field] = value; //更新缓存中的值
-
- 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];
- that.eachCols(function(i, item){
- if(item.field == field && item.templet){
- templet = item.templet;
- }
- });
- othis.siblings(ELEM_CELL).html(
- templet ? laytpl($(templet).html() || this.value).render(data) : this.value
- );
- othis.parent().data('content', this.value);
- othis.remove();
- });
-
- //单元格事件
- that.layBody.on('click', 'td', function(){
- var othis = $(this)
- ,field = othis.data('field')
- ,editType = othis.data('edit')
- ,elemCell = othis.children(ELEM_CELL);
-
- layer.close(that.tipsIndex);
- if(othis.data('off')) return;
-
- //显示编辑表单
- if(editType){
- if(editType === 'select') { //选择框
- //var select = $('');
- //othis.find('.'+ELEM_EDIT)[0] || othis.append(select);
- } else { //输入框
- var 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){
- 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;
+ $(options.cols).each(function (index, item1) {
+ layui.each(item1, function (i2, item2) {
+ if (item2.hidden == true) {
+ hideCols.push(item2);
+ } else {
+ showCols.push(item2);
}
- });
- td.children(ELEM_CELL).html(
- templet ? laytpl($(templet).html() || value).render(data) : value
- );
- td.data('content', value);
- }
- });
+ });
+ });
+ options.hideCols = [hideCols];
+ options.showCols = [showCols];
+
+ 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.layPage = reElem.find(ELEM_PAGE);
+
+ 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')));
}
- });
- 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();
- });
- };
-
- //初始化
- 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.checkStatus = function(id){
- 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));
- }
- });
- return {
- data: arr //选中的数据
- ,isAll: data.length ? (nums === (data.length - invalidNum)) : false //是否全选
+ table.cache.AllData = that;
+ //请求数据
+ // that.pullData(that.page);
+ that.events();
};
- };
-
- //表格重载
- 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.render = function(options){
- var inst = new Class(options);
- return thisTable.call(inst);
- };
-
- //清除临时Key
- table.clearCacheKey = function(data){
- data = $.extend({}, data);
- delete data[table.config.checkName];
- delete data[table.config.indexName];
- return data;
- };
-
- //自动完成渲染
- table.init();
-
- exports(MOD_NAME, table);
-});
-
+ //根据列类型,定制化参数
+ 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 getWidth(parent) {
+ var width, isNone;
+ parent = parent || options.elem.parent();
+ width = parent.width();
+ isNone = parent.css('display') === 'none';
+ 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.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 sort() {
+ if (_typeof(options.initSort) === 'object') {
+ that.sort(options.initSort.field, options.initSort.type);
+ }
+ }
+ ;
+ that.startTime = new Date().getTime(); //渲染开始时间
+
+ if (options.url) {
+ //Ajax请求
+ var params = {};
+ params[request.pageName] = curr;
+ params[request.limitName] = options.limit;
+ that.loading();
+ $.ajax({
+ type: options.method || 'post',
+ url: options.url,
+ data: $.extend(params, options.where),
+ dataType: 'json',
+ success: function success(res) {
+ if (res[response.statusName] != response.statusCode) {
+ that.renderForm();
+ return that.layMain.html('' + (res[response.msgName] || '返回的数据状态异常') + '
');
+ }
+
+ that.renderData(res, curr, res[response.countName][response.pageRecords]), sort();
+ options.time = new Date().getTime() - that.startTime + ' ms'; //耗时(接口请求+视图渲染)
+ loadIndex && layer.close(loadIndex);
+ typeof options.done === 'function' && options.done(res, curr, res[response.countName][response.pageRecords]);
+ options.clearArray(res);
+ },
+ complete: function complete() {
+ that.loading(true);
+ },
+ error: function error(e, m) {
+ that.layMain.html('数据接口请求异常
');
+ that.renderForm();
+ loadIndex && layer.close(loadIndex);
+ }
+ });
+ } else if (options.data && options.data.constructor === Array) {
+ //已知数据
+ var res = {},
+ startLimit = curr * options.limit - options.limit;
+
+ res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
+ res[response.countName][response.pageRecords] = options.data.length;
+
+ that.renderData(res, curr, options.data.length), sort();
+ typeof options.done === 'function' && options.done(res, curr, res[response.countName][response.pageRecords]);
+ }
+ };
+
+ //遍历表头
+ 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 eachArrs(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 render() {
+ //后续性能提升的重点
+ // if (!sort && that.sortKey) {
+ // return that.sort(that.sortKey.field, that.sortKey.sort, true);
+ // }
+
+ layui.each(data, function (i1, item1) {
+ var tds = [],
+ tds_fixed = [],
+ tds_fixed_r = [],
+ trAttr = "",
+ trColor = "",
+ numbers = i1 + options.limit * (curr - 1) + 1; //序号
+
+ if (item1.length === 0) return;
+ if (!sort) {
+ item1[table.config.indexName] = i1;
+ }
+ if (item1.color) {
+ trColor = 'style="color:' + item1.color + '"';
+ }
+ that.eachCols(function (i3, item3) {
+ var field = item3.field || i3,
+ content = item1[field],
+ cell = that.getColElem(that.layHeader, field);
+
+ if (content === undefined || content === null) content = '';
+ if (item3.colspan > 1) return;
+
+ //td内容
+ var td = ['', '' + function () {
+ var tplData = $.extend(true, {
+ LAY_INDEX: numbers
+ }, item1);
+
+ //渲染复选框列视图
+ if (item3.type === 'checkbox') {
+ return ' ';
+ } else if (item3.type === 'numbers') {
+ //渲染序号
+ return numbers;
+ }
+
+ if (item3.type == 'video') {
+ return ' ';
+ }
+
+ //解析工具列模板
+ if (item3.toolbar) {
+ var toolBox = '';
+ $(item3.toolbar.btn).each(function (index, tool) {
+ toolBox += ' ' + tool.name + '';
+ });
+ return laytpl(toolBox).render(tplData);
+ }
+
+ return item3.templet ? 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);
+ });
+
+ $(that.config.hideCols).each(function (index, el1) {
+ //隐藏域赋值
+ $(el1).each(function (index, el2) {
+ trAttr += 'data-id' + '=\'' + item1[el2.field] + '\' ';
+ });
+ });
+ trs.push('' + tds.join('') + '
');
+ trs_fixed.push('' + tds_fixed.join('') + '
');
+ trs_fixed_r.push('' + tds_fixed_r.join('') + '
');
+ });
+
+ 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.getDays(res.extendObject);
+ that.key = options.id || options.index;
+ table.cache[that.key] = data; //记录数据
+
+ //排序
+ 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('无数据
');
+ }
+
+ render();
+ //同步分页状态
+ if (options.page) {
+ options.page = $.extend({
+ elem: 'layui-table-page' + options.index,
+ count: count,
+ limit: options.limit,
+ limits: options.limits || [50, 100, 500],
+ groups: 6,
+ // first:'首页',
+ // last:'尾页',
+ layout: ['count', 'currpage', 'limit', 'first', 'prev', 'page', 'next', 'last'],
+ // prev: '',
+ // next: '',
+ jump: function jump(obj, first) {
+ if (!first) {
+ //分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们
+ //而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用)
+ that.page = obj.curr; //更新页码
+ options.limit = obj.limit; //更新每页条数
+
+ that.pullData(obj.curr, that.loading());
+ }
+ }
+ }, options.page);
+ options.page.count = count; //更新总条数
+ laypage.render(options.page);
+ }
+ };
+
+ //案件天数
+ Class.prototype.getDays = function (data) {
+ if ($(".caseControl") && $(".business-icon") && data) {
+ if ($(".caseControl .business-icon a.businBox").length > 0) {
+ var num = 0;
+ $.each(data, function (key, val) {
+ num++;
+ $(".icolor" + num).html(val);
+ });
+ }
+ }
+ };
+
+ //找到对应的列元素
+ 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.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 || th.data('field');
+
+ //如果欲执行的排序已在状态中,则不执行渲染
+ if (that.sortKey && !pull) {
+ if (field === that.sortKey.SortFiled && type === that.sortKey.SortType) {
+ 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 = {
+ SortFiled: field,
+ SortType: type
+ };
+
+ 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;
+ $.extend(true, options.where, that.sortKey);
+ if (that.sortKey !== undefined) {
+ that.pullData(1);
+ }
+
+ // that.renderData(res, that.page, that.count, true);
+ // layer.close(that.tipsIndex);
+ // if (formEvent) {
+ // layui.event.call(th, MOD_NAME, 'sort(' + filter + ')', {
+ // field: field,
+ // type: type
+ // });
+ // }
+ };
+
+ //请求loading
+ Class.prototype.loading = function (isClose) {
+ var that = this,
+ options = that.config,
+ index;
+ index = layer.msg('数据请求中', {
+ icon: 16,
+ offset: [that.elem.offset().top + that.elem.height() / 2 - $(".frameTitle").outerHeight(true) - $(".filter_v2").innerHeight() - $(".caseControl").innerHeight() - 35 - _WIN.scrollTop() + 'px', that.elem.offset().left + that.elem.width() / 2 - 90 - _WIN.scrollLeft() + 'px'],
+ anim: -1,
+ fixed: false
+ });
+ if (isClose == true) {
+ layer.close(index);
+ } else {
+ if (options.loading && options.url) {
+ return index;
+ }
+ }
+ };
+
+ //同步选中值状态
+ 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 syncColsCheck(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)) {
+ 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) - parseFloat(that.layHeader.height()) - $(".frameTitle").outerHeight(true) - $(".filter_v2").innerHeight() - $(".caseControl").innerHeight() - 1;
+
+ if (options.toolbar) {
+ bodyHeight = bodyHeight - that.layTool.outerHeight();
+ }
+ if (options.page) {
+ bodyHeight = bodyHeight - that.layPage.outerHeight() - 1;
+ }
+
+ 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');
+ 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'),
+ indexLayer = 0;
+
+ //拖拽调整宽度
+ 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('field');
+ layui.stope(e);
+ if (index === 0) {
+ that.sort(field, 'asc', null, true);
+ } else {
+ that.sort(field, 'desc', null, true);
+ }
+ });
+
+ //复选框选择
+ 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][index],
+ type: isAll ? 'all' : 'one'
+ });
+ });
+
+ //行事件
+ that.layBody.on('mouseenter', 'tr', function () {
+ var othis = $(this),
+ index = othis.index();
+ that.layBody.find('tr:eq(' + index + ')').addClass(ELEM_HOVER);
+ }).on('mouseleave', 'tr', function () {
+ var othis = $(this),
+ index = othis.index();
+ that.layBody.find('tr:eq(' + index + ')').removeClass(ELEM_HOVER);
+ });
+
+ //单元格编辑
+ 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];
+
+ data[field] = value; //更新缓存中的值
+
+ 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];
+ that.eachCols(function (i, item) {
+ if (item.field == field && item.templet) {
+ templet = item.templet;
+ }
+ });
+ othis.siblings(ELEM_CELL).html(templet ? laytpl($(templet).html() || this.value).render(data) : this.value);
+ othis.parent().data('content', this.value);
+ othis.remove();
+ });
+
+ //单元格事件
+ that.layBody.on('click', 'td', function () {
+ var othis = $(this),
+ field = othis.data('field'),
+ editType = othis.data('edit'),
+ elemCell = othis.children(ELEM_CELL);
+
+ layer.close(that.tipsIndex);
+ if (othis.data('off')) return;
+
+ //显示编辑表单
+ if (editType) {
+ if (editType === 'select') {//选择框
+ //var select = $('');
+ //othis.find('.'+ELEM_EDIT)[0] || othis.append(select);
+ } else {
+ //输入框
+ var input = $('');
+ input[0].value = othis.data('content') || elemCell.text();
+ othis.find('.' + ELEM_EDIT)[0] || othis.append(input);
+ input.focus();
+ }
+ return;
+ }
+
+ //行选中状态
+ if (othis.parents('tr').hasClass('formchecked')) {
+ othis.parents('tr').removeClass('formchecked');
+ } else {
+ that.layBody.find('tr').removeClass('formchecked');
+ othis.parents('tr').addClass('formchecked');
+ }
+
+ //如果出现省略,则可查看更多
+ // 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) {
+ // layero.find('.layui-table-tips-c').on('click', function() {
+ // layer.close(index);
+ // });
+ // }
+ // });
+ // }
+ });
+
+ //显示更多tips
+ that.layBody.on('mouseover mouseout', 'td.openTip', function () {
+ var othis = $(this),
+ elemCell = othis.children('.layui-table-cell');
+
+ if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
+ othis.attr("id", elemCell.attr("class").split(" ")[1]);
+
+ if (event.type == "mouseover") {
+ indexLayer = layer.tips(elemCell.html(), elemCell[0], {
+ tips: [2, '#3595CC'],
+ time: 0
+ });
+ }
+ if (event.type == "mouseout") {
+ layer.close(indexLayer);
+ }
+ }
+ });
+
+ //工具条操作事件
+ 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 del() {
+ table.cache[that.key][index] = [];
+ tr.remove();
+ that.scrollPatch();
+ },
+ update: function update(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);
+ }
+ });
+ }
+ });
+ tr.addClass(ELEM_CLICK).siblings('tr').removeClass(ELEM_CLICK);
+ });
+
+ //工具条新操作事件
+ that.layBody.on('click', '.operatBox a', function () {
+ var othis = $(this),
+ index = othis.parents('tr').eq(0).data('index'),
+ indexCols = othis.data('tool'),
+ tr = that.layBody.find('tr[data-index="' + index + '"]'),
+ ELEM_CLICK = 'layui-table-click',
+ data = table.cache[that.key][index],
+ cols = that.config.cols[0],
+ operatCont = [];
+ $.grep(cols, function (item, index) {
+ if (item.field == "operatBox") {
+ return operatCont.push(cols[index].toolbar.btn);
+ }
+ });
+ operatCont = operatCont[0];
+ operatCont[indexCols].event(data);
+ });
+
+ // 双击执行函数
+ that.layBody.on('dblclick', 'td', function (event) {
+ var othis = $(this),
+ td = othis.parents('tr').find('td[data-field="operatBox"]'),
+ dblTool;
+ if (td !== undefined) {
+ dblTool = td.find('a').eq(0); //默认执行第一个函数
+ $(dblTool).trigger('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();
+ });
+ };
+
+ //初始化
+ 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.checkStatus = function (id) {
+ var nums = 0,
+ invalidNum = 0,
+ arr = [],
+ data = table.cache[id];
+ if (!data) return {};
+ //计算全选个数
+ layui.each(data, function (i, item) {
+ if (item.constructor === Array) {
+ invalidNum++; //无效数据,或已删除的
+ return;
+ }
+ if (item[table.config.checkName]) {
+ nums++;
+ arr.push(table.clearCacheKey(item));
+ }
+ });
+ return {
+ data: arr //选中的数据
+
+ , isAll: nums === data.length - invalidNum //是否全选
+ };
+ };
+ //表格重载
+ 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.reloadData = function (data) {
+ $.extend(true, table.cache.AllData.config.where, data);
+ Class.prototype.pullData.call(table.cache.AllData,1);
+ };
+
+ //核心入口
+ table.render = function (options) {
+ var inst = new Class(options);
+ if (options.elem !== undefined && options.elem.indexOf("#") !== -1) {
+ return thisTable.call(inst);
+ } else {
+ console.log('没有容器对象,检查viewId,是否有加#');
+ }
+ };
+
+ //清除临时Key
+ table.clearCacheKey = function (data) {
+ data = $.extend({}, data);
+ delete data[table.config.checkName];
+ delete data[table.config.indexName];
+ return data;
+ };
+
+ //自动完成渲染
+ table.init();
+
+ exports(MOD_NAME, table);
+});
\ No newline at end of file
diff --git a/src/layuiModel-2.js b/src/layuiModel-2.js
new file mode 100644
index 00000000..ae283414
--- /dev/null
+++ b/src/layuiModel-2.js
@@ -0,0 +1,412 @@
+"use strict";
+
+/*
+ * 2017.10.19
+ * xzb
+ */
+
+var layConfig = {},
+ layInit = function(options,selectData) {
+ /*
+ * 传入参数
+ * url 数据地址
+ * numpage 每页出现的数据量 默认为 10
+ * title 表格标题
+ */
+ var that = this,
+ initData,
+ jwidth = ($(window).width() !== 0) ? $(window).width() : Number($.cookie("cookieBefore").split("$")[0]),
+ jheight = ($(window).height() !== 0) ? $(window).height() : Number($.cookie("cookieBefore").split("$")[1]),
+ defaults = {
+ elem:"",
+ id:"",
+ url: "",
+ width: jwidth,
+ height: jheight,
+ numpage: 50,
+ limits:"",
+ page: true,
+ where:"",
+ initSort: "",
+ done :""
+ };
+ if($(window).width() !== 0 && $(window).height() !== 0) {
+ $.cookie("cookieBefore", $(window).width() + "$" + $(window).height(), {path: "/" });
+ }
+
+ initData = $.extend(true,defaults, options);
+ return new layInit.prototype.init(initData,selectData);
+ },
+ layPaging = function(data) {
+ var paging = {where:data},
+ newData = $.extend(true,{},layConfig.RenderJson,paging)
+ ;
+ layui.use(['table'], function() {
+ var table = layui.table,
+ reloadId = newData.elem.split("#")[1]
+ ;
+ table.reload(reloadId, newData);
+ //table.renderData();
+ // table.reloadData(reloadId, newData);
+ })
+ },
+ layWindow = {}
+;
+
+layInit.prototype = {
+ init : function(data,selectData) {
+ var that = this,
+ RenderJson
+ ;
+ RenderJson = {
+ elem: data.viewId,
+ id: data.id,
+ cols: [data.columns],
+ url: data.url,
+ width: data.width,
+ height: data.height,
+ limit: data.numpage,
+ limits: data.limits,
+ page: data.page,
+ initSort: data.initSort,
+ clearArray:that.events.clearArray,
+ where: data.where || selectData,
+ done : function (res, curr, count){
+ if(data.done) {
+ data.done.event(res, curr, count);
+ }
+ }
+ };
+
+ if($(RenderJson.elem).attr('lay-filter') == undefined) {
+ $(RenderJson.elem).attr('lay-filter',"LAY-table-1");
+ }
+
+ layConfig['RenderJson'] = RenderJson;
+ layui.use(['table', 'form', 'layer', 'jquery'], function() {
+ var table = layui.table,
+ form = layui.form,
+ layer = parent.layer,
+ $ = layui.jquery,
+ checboxFid = [],
+ checkId = data.viewId.split("#")[1]
+ ;
+ if(table.cache.PageList == undefined) {
+ table.render(RenderJson);
+ }
+ table.reloadData(selectData);
+
+ table.on('checkbox(LAY-table-1)', function(obj){
+ var checkStatus = table.checkStatus(checkId); //test即为基础参数id对应的值
+ if(!layConfig.jChecbox) {
+ checboxFid = [];
+ }
+ if(obj.type == 'all') {
+ if(obj.checked){
+ checboxFid = [];
+ $(checkStatus.data).each(function(index, item) {
+ checboxFid.push(item.FID)
+ });
+ } else {
+ checboxFid = [];
+ }
+ } else {
+ if(obj.checked){
+ checboxFid.push(obj.data.FID);
+ } else {
+ checboxFid = $.grep(checboxFid, function(value) {
+ return value != obj.data.FID;
+ });
+ }
+ }
+ layConfig.jChecbox = checboxFid;
+ // console.log(obj.checked); //当前是否选中状态
+ // console.log(obj.data.FID); //选中行的相关数据
+ // console.log(obj.type); //如果触发的是全选,则为:all,如果触发的是单选,则为:one
+ });
+ })
+ },
+ events : {
+ clearArray : function(checkStatus){ // 事件处理
+ var that = this;
+ layConfig.checkStatus = null; //将选中项值置为空
+ layConfig.jChecbox = null;
+ layConfig.checkStatus = checkStatus.object;
+ }
+ }
+}
+
+layInit.prototype.init.prototype = layInit.prototype;
+
+layWindow = {
+ /*
+ *打开layer弹窗
+ *OConfig 弹窗配置
+ *title 标题
+ *href 地址
+ *boxArea 宽高,
+ */
+ layerOpen: function layerOpen(OConfig, callback) {
+ // 阻止event默认行为 a标签的跳转
+ // event.preventDefault();//支持DOM标准的浏览器
+ // event.returnValue = false;//IE
+ var boxSize = [],
+ boxWidth,
+ boxheight,
+ boxType,
+ boxShade
+ ;
+ if (OConfig.boxArea == "" || OConfig.boxArea == null) {
+ //判断页面高度
+ boxWidth = 1200 + 'px';
+ boxheight = 600 + 'px';
+ } else if (OConfig.boxArea.width == "auto" || OConfig.boxArea.height == "auto") {
+ boxWidth = "100%";
+ boxheight = "100%";
+ } else {
+ boxWidth = OConfig.boxArea.width + 'px';
+ boxheight = OConfig.boxArea.height + 'px';
+ }
+ //判断是否有遮罩
+ boxShade = (OConfig.closeShade == true) ? 0 : 0.3;
+ boxSize.push(boxWidth, boxheight);
+
+ layui.use(['layer'], function() {
+ var layer = layui.layer;
+
+ var index = layer.open({
+ id: 'UrgeEdit',
+ type: 2,
+ title: OConfig.title,
+ area: boxSize,
+ shade:boxShade,
+ anim: 0,
+ resize: true,
+ content: [OConfig.href] //iframe的url,no代表不显示滚动条
+
+ ,
+ success: function success(event, index) {
+ //给予index属性
+ event.attr("lr-index", index);
+ },
+ cancel: function cancel() {
+ //右上角关闭按钮触发的回调
+ //回调函数
+ if (callback) {
+ callback();
+ }
+ }
+ });
+ if (OConfig.maxmin == true) {
+ layer.full(index);
+ }
+ });
+
+ //layer.full(index);
+ },
+ /*
+ * index 弹出框 自动关闭
+ */
+ layerPopup: function layerPopup(OConfig, callback) {
+ var layOffset = OConfig.offset || 'rb',
+ latTime = OConfig.time || 6000,
+ btnClick = OConfig.btnClick == "null" ? "" : OConfig.btnClick,
+ boxSize = [],
+ boxWidth,
+ boxheight;
+ if (OConfig.boxArea == "" || OConfig.boxArea == null) {
+ //判断页面高度
+ boxWidth = 300;
+ boxheight = 200;
+ } else {
+ boxWidth = OConfig.boxArea.width;
+ boxheight = OConfig.boxArea.height;
+ }
+ boxSize.push(boxWidth + 'px', boxheight + 'px');
+ layui.use(['layer'], function() {
+ layer.open({
+ type: 1,
+ offset: layOffset,
+ id: 'LAY_demo', //防止重复弹出
+ time: latTime,
+ area: boxSize,
+ content: '' + OConfig.content + '
',
+ btn: btnClick,
+ btnAlign: 'c', //按钮居中
+ shade: 0, //不显示遮罩
+ yes: function yes(index) {
+ if (callback) {
+ callback();
+ }
+ layer.close(index);
+ }
+ });
+ });
+ },
+ /*
+ *layerPrompt 输入层
+ *PConfig 弹窗配置参数
+ *
+ *PConfig.title 标题名字 type:string 可缺省
+ *PConfig.formType 输入框类型 type:number 可缺省
+ *支持0(文本)默认1(密码)2(多行文本)
+ *PConfig.boxArea 宽高 type:object 可缺省
+ *PConfig.value 默认值 type:string 可缺省
+ */
+ layerPrompt: function layerPrompt(PConfig, execute) {
+ var boxSize = [],
+ boxWidth,
+ boxheight;
+
+ if (PConfig.boxArea == "" || PConfig.boxArea == null) {
+ //判断页面高度
+ boxWidth = 300;
+ boxheight = 100;
+ } else {
+ boxWidth = PConfig.boxArea.width;
+ boxheight = PConfig.boxArea.height;
+ }
+
+ boxSize.push(boxWidth + 'px', boxheight + 'px');
+
+ layui.use(['layer'], function() {
+ var layer = layui.layer;
+ layer.prompt({
+ formType: PConfig.formType || 0,
+ value: PConfig.value || "",
+ title: PConfig.title || "输入层",
+ area: boxSize //自定义文本域宽高
+ }, function(value, index, elem) {
+ execute(value, elem); //执行事件
+ layer.close(index);
+ });
+ });
+ },
+ /**
+ * layerConfirm 询问框
+ * @param {[string]} content [提示内容]
+ * @param {[object]} options [标题,标签]
+ * @param {[function]} yes [确定事件]
+ * @param {[function]} cancel [取消事件]
+ */
+ layerConfirm: function layerConfirm(content, options, yes, cancel) {
+ layui.use(['layer'], function() {
+ var layer = layui.layer;
+ layer.confirm(content, options, function(index) {
+ yes();
+ layer.close(index);
+ }, cancel);
+ });
+ },
+ /**
+ * layMsg 提示框
+ * @param {[string]} content [提示内容]
+ * @param {[function]} options [关闭后执行事件]
+ */
+ layMsg: function layMsg(content, callback, time) {
+ layui.use(['layer'], function() {
+ var layer = layui.layer;
+ layer.msg(content, {
+ time: time || 2000
+ }, callback);
+ });
+ },
+ layerLoad: function layerLoad(isClose, index) {
+ if (!isClose) {
+ var layShade = '\n ';
+
+ $("body").append(layShade);
+
+ } else {
+ $(".layui-layer-shade,.layui-layer-loading").remove();
+ }
+ },
+ //关闭自身
+ layerCloseSelf: function layerCloseSelf(callback) {
+ var index;
+ layui.use(['layer'], function() {
+ //关闭当前iframe,parent找不到就去top找
+ if (parent.layer.getFrameIndex(window.name)) {
+ if (callback) {
+ callback();
+ }
+
+ index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
+ parent.layWindow.layerClose(index); //再执行关闭
+ } else {
+ if (callback) {
+ callback();
+ }
+ index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
+ top.layWindow.layerClose(index); //再执行关闭
+ }
+ });
+ },
+ //关闭所有
+ layerCloseAll: function layerCloseAll() {
+ layui.use(['layer'], function() {
+ layer.closeAll();
+ });
+ },
+ layerClose: function layerClose(index) {
+ layui.use(['layer'], function() {
+ layer.close(index);
+ });
+ },
+ /*
+ * input 自动补全
+ */
+ completion: function completion(config, callback) {
+ var tautocomp = $("#" + config.id).tautocomplete({
+ columns: config.columns,
+ delay: 1000,
+ ajax: {
+ url: config.url,
+ type: "GET",
+ data: function data() {
+ var x = {
+ SearchText: tautocomp.searchdata()
+ };
+ return x;
+ },
+ success: function success(data) {
+ return data.object;
+ }
+ },
+ onchange: function onchange() {}
+ }, callback);
+ },
+ /*
+ * 时间轴插件
+ */
+ timeAxis: function timeAxis(config) {
+ var AxisId = $('#' + config.id);
+ $.fn.axisOption = function(data) {
+ var jThis = $(this);
+ $.ajax({
+ url: data,
+ type: 'GET',
+ dataType: "JSON",
+ success: loopData
+ });
+
+ function loopData(oData) {
+ var dataTpl = "";
+ if (oData.object !== null) {
+ AxisId.append("");
+ $(oData.object).each(function(index, item) {
+
+ if (item.complete == true) {
+ dataTpl += "\n " + item.title + "\n \u5B8C\u6210\n " + item.time + "\n ";
+ } else {
+ dataTpl += "\n " + item.title + "\n \u672A\u5B8C\u6210\n " + item.time + "\n ";
+ }
+ });
+ jThis.find('.container').html("");
+ }
+
+ }
+ };
+ AxisId.axisOption(config.url);
+ }
+}