table.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  1. /**
  2. @Name:layui.table 表格操作
  3. @Author:贤心
  4. @License:MIT
  5. */
  6. layui.define(['laytpl', 'laypage', 'layer', 'form', 'util','laydate'], function(exports){
  7. "use strict";
  8. var $ = layui.$
  9. ,laytpl = layui.laytpl
  10. ,laypage = layui.laypage
  11. ,layer = layui.layer
  12. ,form = layui.form
  13. ,util = layui.util
  14. ,laydate = layui.laydate
  15. ,hint = layui.hint()
  16. ,device = layui.device()
  17. //外部接口
  18. ,table = {
  19. config: {
  20. checkName: 'LAY_CHECKED' //是否选中状态的字段名
  21. ,indexName: 'LAY_TABLE_INDEX' //下标索引名
  22. } //全局配置项
  23. ,cache: {} //数据缓存
  24. ,index: layui.table ? (layui.table.index + 10000) : 0
  25. //设置全局项
  26. ,set: function(options){
  27. var that = this;
  28. that.config = $.extend({}, that.config, options);
  29. return that;
  30. }
  31. //事件监听
  32. ,on: function(events, callback){
  33. return layui.onevent.call(this, MOD_NAME, events, callback);
  34. }
  35. }
  36. //操作当前实例
  37. ,thisTable = function(){
  38. var that = this
  39. ,options = that.config
  40. ,id = options.id || options.index;
  41. if(id){
  42. thisTable.that[id] = that; //记录当前实例对象
  43. thisTable.config[id] = options; //记录当前实例配置项
  44. }
  45. return {
  46. reload: function(options){
  47. that.reload.call(that, options);
  48. }
  49. ,setColsWidth: function(){
  50. that.setColsWidth.call(that);
  51. }
  52. ,resize: function(){ //重置表格尺寸/结构
  53. that.resize.call(that);
  54. }
  55. ,config: options
  56. }
  57. }
  58. //获取当前实例配置项
  59. ,getThisTableConfig = function(id){
  60. var config = thisTable.config[id];
  61. if(!config) hint.error('The ID option was not found in the table instance');
  62. return config || null;
  63. }
  64. //字符常量
  65. ,MOD_NAME = 'table', ELEM = '.layui-table', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled', NONE = 'layui-none'
  66. ,ELEM_VIEW = 'layui-table-view', ELEM_TOOL = '.layui-table-tool', ELEM_BOX = '.layui-table-box', ELEM_INIT = '.layui-table-init', 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_TOTAL = '.layui-table-total', ELEM_PAGE = '.layui-table-page', ELEM_SORT = '.layui-table-sort', ELEM_EDIT = 'layui-table-edit', ELEM_HOVER = 'layui-table-hover'
  67. //thead区域模板
  68. ,TPL_HEADER = function(options){
  69. var rowCols = '{{#if(item2.colspan){}} colspan="{{item2.colspan}}"{{#} if(item2.rowspan){}} rowspan="{{item2.rowspan}}"{{#}}}';
  70. options = options || {};
  71. return ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
  72. ,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
  73. ,'<thead>'
  74. ,'{{# layui.each(d.data.cols, function(i1, item1){ }}'
  75. ,'<tr>'
  76. ,'{{# layui.each(item1, function(i2, item2){ }}'
  77. ,'{{# if(item2.fixed && item2.fixed !== "right"){ left = true; } }}'
  78. ,'{{# if(item2.fixed === "right"){ right = true; } }}'
  79. ,function(){
  80. if(options.fixed && options.fixed !== 'right'){
  81. return '{{# if(item2.fixed && item2.fixed !== "right"){ }}';
  82. }
  83. if(options.fixed === 'right'){
  84. return '{{# if(item2.fixed === "right"){ }}';
  85. }
  86. return '';
  87. }()
  88. ,'{{# var isSort = !(item2.colGroup) && item2.sort; }}'
  89. ,'<th data-field="{{ item2.field||i2 }}" data-key="{{d.index}}-{{i1}}-{{i2}}" {{# if( item2.parentKey){ }}data-parentkey="{{ item2.parentKey }}"{{# } }} {{# if(item2.minWidth){ }}data-minwidth="{{item2.minWidth}}"{{# } }} '+ rowCols +' {{# if(item2.unresize || item2.colGroup){ }}data-unresize="true"{{# } }} class="{{# if(item2.hide){ }}layui-hide{{# } }}{{# if(isSort){ }} layui-unselect{{# } }}{{# if(!item2.field){ }} layui-table-col-special{{# } }}">'
  90. ,'<div class="layui-table-cell laytable-cell-'
  91. ,'{{# if(item2.colGroup){ }}'
  92. ,'group'
  93. ,'{{# } else { }}'
  94. ,'{{d.index}}-{{i1}}-{{i2}}'
  95. ,'{{# if(item2.type !== "normal"){ }}'
  96. ,' laytable-cell-{{ item2.type }}'
  97. ,'{{# } }}'
  98. ,'{{# } }}'
  99. ,'" {{#if(item2.align){}}align="{{item2.align}}"{{#}}}>'
  100. ,'{{# if(item2.type === "checkbox"){ }}' //复选框
  101. ,'<input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose" {{# if(item2[d.data.checkName]){ }}checked{{# }; }}>'
  102. ,'{{# } else { }}'
  103. ,'<span>{{item2.title||""}}</span>'
  104. ,'{{# if(isSort){ }}'
  105. ,'<span class="layui-table-sort layui-inline"><i class="layui-edge layui-table-sort-asc" title="升序"></i><i class="layui-edge layui-table-sort-desc" title="降序"></i></span>'
  106. ,'{{# } }}'
  107. ,'{{# } }}'
  108. ,'</div>'
  109. ,'</th>'
  110. ,(options.fixed ? '{{# }; }}' : '')
  111. ,'{{# }); }}'
  112. ,'</tr>'
  113. ,'{{# }); }}'
  114. ,'</thead>'
  115. ,'</table>'].join('');
  116. }
  117. //tbody区域模板
  118. ,TPL_BODY = ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
  119. ,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
  120. ,'<tbody></tbody>'
  121. ,'</table>'].join('')
  122. //主模板
  123. ,TPL_MAIN = ['<div class="layui-form layui-border-box {{d.VIEW_CLASS}}" lay-filter="LAY-table-{{d.index}}" lay-id="{{ d.data.id }}" style="{{# if(d.data.width){ }}width:{{d.data.width}}px;{{# } }} {{# if(d.data.height){ }}height:{{d.data.height}}px;{{# } }}">'
  124. ,'{{# if(d.data.toolbar){ }}'
  125. ,'<div class="layui-table-tool">'
  126. ,'<div class="layui-table-tool-temp"></div>'
  127. ,'<div class="layui-table-tool-self"></div>'
  128. ,'</div>'
  129. ,'{{# } }}'
  130. ,'<div class="layui-table-box">'
  131. ,'{{# if(d.data.loading){ }}'
  132. ,'<div class="layui-table-init" style="background-color: #fff;">'
  133. ,'<i class="layui-icon layui-icon-loading layui-icon"></i>'
  134. ,'</div>'
  135. ,'{{# } }}'
  136. ,'{{# var left, right; }}'
  137. ,'<div class="layui-table-header">'
  138. ,TPL_HEADER()
  139. ,'</div>'
  140. ,'<div class="layui-table-body layui-table-main">'
  141. ,TPL_BODY
  142. ,'</div>'
  143. ,'{{# if(left){ }}'
  144. ,'<div class="layui-table-fixed layui-table-fixed-l">'
  145. ,'<div class="layui-table-header">'
  146. ,TPL_HEADER({fixed: true})
  147. ,'</div>'
  148. ,'<div class="layui-table-body">'
  149. ,TPL_BODY
  150. ,'</div>'
  151. ,'</div>'
  152. ,'{{# }; }}'
  153. ,'{{# if(right){ }}'
  154. ,'<div class="layui-table-fixed layui-table-fixed-r">'
  155. ,'<div class="layui-table-header">'
  156. ,TPL_HEADER({fixed: 'right'})
  157. ,'<div class="layui-table-mend"></div>'
  158. ,'</div>'
  159. ,'<div class="layui-table-body">'
  160. ,TPL_BODY
  161. ,'</div>'
  162. ,'</div>'
  163. ,'{{# }; }}'
  164. ,'</div>'
  165. ,'{{# if(d.data.totalRow){ }}'
  166. ,'<div class="layui-table-total">'
  167. ,'<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
  168. ,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
  169. ,'<tbody><tr><td><div class="layui-table-cell" style="visibility: hidden;">Total</div></td></tr></tbody>'
  170. , '</table>'
  171. ,'</div>'
  172. ,'{{# } }}'
  173. ,'{{# if(d.data.page){ }}'
  174. ,'<div class="layui-table-page">'
  175. ,'<div id="layui-table-page{{d.index}}"></div>'
  176. ,'</div>'
  177. ,'{{# } }}'
  178. ,'<style>'
  179. ,'{{# layui.each(d.data.cols, function(i1, item1){'
  180. ,'layui.each(item1, function(i2, item2){ }}'
  181. ,'.laytable-cell-{{d.index}}-{{i1}}-{{i2}}{ '
  182. ,'{{# if(item2.width){ }}'
  183. ,'width: {{item2.width}}px;'
  184. ,'{{# } }}'
  185. ,' }'
  186. ,'{{# });'
  187. ,'}); }}'
  188. ,'</style>'
  189. ,'</div>'].join('')
  190. ,_WIN = $(window)
  191. ,_DOC = $(document)
  192. //构造器
  193. ,Class = function(options){
  194. var that = this;
  195. that.index = ++table.index;
  196. that.config = $.extend({}, that.config, table.config, options);
  197. that.render();
  198. };
  199. //默认配置
  200. Class.prototype.config = {
  201. limit: 10 //每页显示的数量
  202. ,loading: true //请求数据时,是否显示loading
  203. ,cellMinWidth: 60 //所有单元格默认最小宽度
  204. ,defaultToolbar: ['filter', 'exports', 'print'] //工具栏右侧图标
  205. ,autoSort: true //是否前端自动排序。如果否,则需自主排序(通常为服务端处理好排序)
  206. ,text: {
  207. none: '无数据'
  208. }
  209. };
  210. //表格渲染
  211. Class.prototype.render = function(){
  212. var that = this
  213. ,options = that.config;
  214. options.elem = $(options.elem);
  215. options.where = options.where || {};
  216. options.id = options.id || options.elem.attr('id') || that.index;
  217. //请求参数的自定义格式
  218. options.request = $.extend({
  219. pageName: 'page'
  220. ,limitName: 'limit'
  221. }, options.request)
  222. //响应数据的自定义格式
  223. options.response = $.extend({
  224. statusName: 'code'
  225. ,statusCode: 0
  226. ,msgName: 'msg'
  227. ,dataName: 'data'
  228. ,countName: 'count'
  229. }, options.response);
  230. //如果 page 传入 laypage 对象
  231. if(typeof options.page === 'object'){
  232. options.limit = options.page.limit || options.limit;
  233. options.limits = options.page.limits || options.limits;
  234. that.page = options.page.curr = options.page.curr || 1;
  235. delete options.page.elem;
  236. delete options.page.jump;
  237. }
  238. if(!options.elem[0]) return that;
  239. //高度铺满:full-差距值
  240. if(options.height && /^full-\d+$/.test(options.height)){
  241. that.fullHeightGap = options.height.split('-')[1];
  242. options.height = _WIN.height() - that.fullHeightGap;
  243. }
  244. //初始化一些参数
  245. that.setInit();
  246. //开始插入替代元素
  247. var othis = options.elem
  248. ,hasRender = othis.next('.' + ELEM_VIEW)
  249. //主容器
  250. ,reElem = that.elem = $(laytpl(TPL_MAIN).render({
  251. VIEW_CLASS: ELEM_VIEW
  252. ,data: options
  253. ,index: that.index //索引
  254. }));
  255. options.index = that.index;
  256. //生成替代元素
  257. hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender
  258. othis.after(reElem);
  259. //各级容器
  260. that.layTool = reElem.find(ELEM_TOOL);
  261. that.layBox = reElem.find(ELEM_BOX);
  262. that.layHeader = reElem.find(ELEM_HEADER);
  263. that.layMain = reElem.find(ELEM_MAIN);
  264. that.layBody = reElem.find(ELEM_BODY);
  265. that.layFixed = reElem.find(ELEM_FIXED);
  266. that.layFixLeft = reElem.find(ELEM_FIXL);
  267. that.layFixRight = reElem.find(ELEM_FIXR);
  268. that.layTotal = reElem.find(ELEM_TOTAL);
  269. that.layPage = reElem.find(ELEM_PAGE);
  270. //初始化工具栏
  271. that.renderToolbar();
  272. //让表格平铺
  273. that.fullSize();
  274. //如果多级表头,则填补表头高度
  275. if(options.cols.length > 1){
  276. //补全高度
  277. var th = that.layFixed.find(ELEM_HEADER).find('th');
  278. th.height(that.layHeader.height() - 1 - parseFloat(th.css('padding-top')) - parseFloat(th.css('padding-bottom')));
  279. }
  280. that.pullData(that.page); //请求数据
  281. that.events(); //事件
  282. };
  283. //根据列类型,定制化参数
  284. Class.prototype.initOpts = function(item){
  285. var that = this
  286. ,options = that.config
  287. ,initWidth = {
  288. checkbox: 48
  289. ,radio: 48
  290. ,space: 15
  291. ,numbers: 40
  292. };
  293. //让 type 参数兼容旧版本
  294. if(item.checkbox) item.type = "checkbox";
  295. if(item.space) item.type = "space";
  296. if(!item.type) item.type = "normal";
  297. if(item.type !== "normal"){
  298. item.unresize = true;
  299. item.width = item.width || initWidth[item.type];
  300. }
  301. };
  302. //初始化一些参数
  303. Class.prototype.setInit = function(type){
  304. var that = this
  305. ,options = that.config;
  306. options.clientWidth = options.width || function(){ //获取容器宽度
  307. //如果父元素宽度为0(一般为隐藏元素),则继续查找上层元素,直到找到真实宽度为止
  308. var getWidth = function(parent){
  309. var width, isNone;
  310. parent = parent || options.elem.parent()
  311. width = parent.width();
  312. try {
  313. isNone = parent.css('display') === 'none';
  314. } catch(e){}
  315. if(parent[0] && (!width || isNone)) return getWidth(parent.parent());
  316. return width;
  317. };
  318. return getWidth();
  319. }();
  320. if(type === 'width') return options.clientWidth;
  321. //初始化列参数
  322. layui.each(options.cols, function(i1, item1){
  323. layui.each(item1, function(i2, item2){
  324. //如果列参数为空,则移除
  325. if(!item2){
  326. item1.splice(i2, 1);
  327. return;
  328. }
  329. item2.key = i1 + '-' + i2;
  330. item2.hide = item2.hide || false;
  331. //设置列的父列索引
  332. //如果是组合列,则捕获对应的子列
  333. if(item2.colGroup || item2.colspan > 1){
  334. var childIndex = 0;
  335. layui.each(options.cols[i1 + 1], function(i22, item22){
  336. //如果子列已经被标注为{HAS_PARENT},或者子列累计 colspan 数等于父列定义的 colspan,则跳出当前子列循环
  337. if(item22.HAS_PARENT || (childIndex > 1 && childIndex == item2.colspan)) return;
  338. item22.HAS_PARENT = true;
  339. item22.parentKey = i1 + '-' + i2;
  340. childIndex = childIndex + parseInt(item22.colspan > 1 ? item22.colspan : 1);
  341. });
  342. item2.colGroup = true; //标注是组合列
  343. }
  344. //根据列类型,定制化参数
  345. that.initOpts(item2);
  346. });
  347. });
  348. };
  349. //初始工具栏
  350. Class.prototype.renderToolbar = function(){
  351. var that = this
  352. ,options = that.config
  353. //添加工具栏左侧模板
  354. var leftDefaultTemp = [
  355. '<div class="layui-inline" lay-event="add"><i class="layui-icon layui-icon-add-1"></i></div>'
  356. ,'<div class="layui-inline" lay-event="update"><i class="layui-icon layui-icon-edit"></i></div>'
  357. ,'<div class="layui-inline" lay-event="delete"><i class="layui-icon layui-icon-delete"></i></div>'
  358. ].join('')
  359. ,elemToolTemp = that.layTool.find('.layui-table-tool-temp');
  360. if(options.toolbar === 'default'){
  361. elemToolTemp.html(leftDefaultTemp);
  362. } else if(typeof options.toolbar === 'string'){
  363. var toolbarHtml = $(options.toolbar).html() || '';
  364. toolbarHtml && elemToolTemp.html(
  365. laytpl(toolbarHtml).render(options)
  366. );
  367. }
  368. //添加工具栏右侧面板
  369. var layout = {
  370. filter: {
  371. title: '筛选列'
  372. ,layEvent: 'LAYTABLE_COLS'
  373. ,icon: 'layui-icon-cols'
  374. }
  375. ,exports: {
  376. title: '导出'
  377. ,layEvent: 'LAYTABLE_EXPORT'
  378. ,icon: 'layui-icon-export'
  379. }
  380. ,print: {
  381. title: '打印'
  382. ,layEvent: 'LAYTABLE_PRINT'
  383. ,icon: 'layui-icon-print'
  384. }
  385. }, iconElem = [];
  386. if(typeof options.defaultToolbar === 'object'){
  387. layui.each(options.defaultToolbar, function(i, item){
  388. var thisItem = layout[item];
  389. if(thisItem){
  390. iconElem.push('<div class="layui-inline" title="'+ thisItem.title +'" lay-event="'+ thisItem.layEvent +'">'
  391. +'<i class="layui-icon '+ thisItem.icon +'"></i>'
  392. +'</div>');
  393. }
  394. });
  395. }
  396. that.layTool.find('.layui-table-tool-self').html(iconElem.join(''));
  397. }
  398. //同步表头父列的相关值
  399. Class.prototype.setParentCol = function(hide, parentKey){
  400. var that = this
  401. ,options = that.config
  402. ,parentTh = that.layHeader.find('th[data-key="'+ options.index +'-'+ parentKey +'"]') //获取父列元素
  403. ,parentColspan = parseInt(parentTh.attr('colspan')) || 0;
  404. if(parentTh[0]){
  405. var arrParentKey = parentKey.split('-')
  406. ,getThisCol = options.cols[arrParentKey[0]][arrParentKey[1]];
  407. hide ? parentColspan-- : parentColspan++;
  408. parentTh.attr('colspan', parentColspan);
  409. parentTh[parentColspan < 1 ? 'addClass' : 'removeClass'](HIDE);
  410. getThisCol.colspan = parentColspan; //同步 colspan 参数
  411. getThisCol.hide = parentColspan < 1; //同步 hide 参数
  412. //递归,继续往上查询是否有父列
  413. var nextParentKey = parentTh.data('parentkey');
  414. nextParentKey && that.setParentCol(hide, nextParentKey);
  415. }
  416. };
  417. //多级表头补丁
  418. Class.prototype.setColsPatch = function(){
  419. var that = this
  420. ,options = that.config
  421. //同步表头父列的相关值
  422. layui.each(options.cols, function(i1, item1){
  423. layui.each(item1, function(i2, item2){
  424. if(item2.hide){
  425. that.setParentCol(item2.hide, item2.parentKey);
  426. }
  427. });
  428. });
  429. };
  430. //动态分配列宽
  431. Class.prototype.setColsWidth = function(){
  432. var that = this
  433. ,options = that.config
  434. ,colNums = 0 //列个数
  435. ,autoColNums = 0 //自动列宽的列个数
  436. ,autoWidth = 0 //自动列分配的宽度
  437. ,countWidth = 0 //所有列总宽度和
  438. ,cntrWidth = that.setInit('width');
  439. //统计列个数
  440. that.eachCols(function(i, item){
  441. item.hide || colNums++;
  442. });
  443. //减去边框差和滚动条宽
  444. cntrWidth = cntrWidth - function(){
  445. return (options.skin === 'line' || options.skin === 'nob') ? 2 : colNums + 1;
  446. }() - that.getScrollWidth(that.layMain[0]) - 1;
  447. //计算自动分配的宽度
  448. var getAutoWidth = function(back){
  449. //遍历所有列
  450. layui.each(options.cols, function(i1, item1){
  451. layui.each(item1, function(i2, item2){
  452. var width = 0
  453. ,minWidth = item2.minWidth || options.cellMinWidth; //最小宽度
  454. if(!item2){
  455. item1.splice(i2, 1);
  456. return;
  457. }
  458. if(item2.colGroup || item2.hide) return;
  459. if(!back){
  460. width = item2.width || 0;
  461. if(/\d+%$/.test(width)){ //列宽为百分比
  462. width = Math.floor((parseFloat(width) / 100) * cntrWidth);
  463. width < minWidth && (width = minWidth);
  464. } else if(!width){ //列宽未填写
  465. item2.width = width = 0;
  466. autoColNums++;
  467. }
  468. } else if(autoWidth && autoWidth < minWidth){
  469. autoColNums--;
  470. width = minWidth;
  471. }
  472. if(item2.hide) width = 0;
  473. countWidth = countWidth + width;
  474. });
  475. });
  476. //如果未填充满,则将剩余宽度平分
  477. (cntrWidth > countWidth && autoColNums) && (
  478. autoWidth = (cntrWidth - countWidth) / autoColNums
  479. );
  480. }
  481. getAutoWidth();
  482. getAutoWidth(true); //重新检测分配的宽度是否低于最小列宽
  483. //记录自动列数
  484. that.autoColNums = autoColNums;
  485. //设置列宽
  486. that.eachCols(function(i3, item3){
  487. var minWidth = item3.minWidth || options.cellMinWidth;
  488. if(item3.colGroup || item3.hide) return;
  489. //给位分配宽的列平均分配宽
  490. if(item3.width === 0){
  491. that.getCssRule(options.index +'-'+ item3.key, function(item){
  492. item.style.width = Math.floor(autoWidth >= minWidth ? autoWidth : minWidth) + 'px';
  493. });
  494. }
  495. //给设定百分比的列分配列宽
  496. else if(/\d+%$/.test(item3.width)){
  497. that.getCssRule(options.index +'-'+ item3.key, function(item){
  498. item.style.width = Math.floor((parseFloat(item3.width) / 100) * cntrWidth) + 'px';
  499. });
  500. }
  501. });
  502. //填补 Math.floor 造成的数差
  503. var patchNums = that.layMain.width() - that.getScrollWidth(that.layMain[0])
  504. - that.layMain.children('table').outerWidth();
  505. if(that.autoColNums && patchNums >= -colNums && patchNums <= colNums){
  506. var getEndTh = function(th){
  507. var field;
  508. th = th || that.layHeader.eq(0).find('thead th:last-child')
  509. field = th.data('field');
  510. if(!field && th.prev()[0]){
  511. return getEndTh(th.prev())
  512. }
  513. return th
  514. }
  515. ,th = getEndTh()
  516. ,key = th.data('key');
  517. that.getCssRule(key, function(item){
  518. var width = item.style.width || th.outerWidth();
  519. item.style.width = (parseFloat(width) + patchNums) + 'px';
  520. //二次校验,如果仍然出现横向滚动条(通常是 1px 的误差导致)
  521. if(that.layMain.height() - that.layMain.prop('clientHeight') > 0){
  522. item.style.width = (parseFloat(item.style.width) - 1) + 'px';
  523. }
  524. });
  525. }
  526. that.loading(!0);
  527. };
  528. //重置表格尺寸/结构
  529. Class.prototype.resize = function(){
  530. var that = this;
  531. that.fullSize(); //让表格铺满
  532. that.setColsWidth(); //自适应列宽
  533. that.scrollPatch(); //滚动条补丁
  534. };
  535. //表格完整重载
  536. Class.prototype.reload = function(options){
  537. var that = this;
  538. if(that.config.data && that.config.data.constructor === Array) delete that.config.data;
  539. that.config = $.extend({}, that.config, options);
  540. that.render();
  541. };
  542. //页码
  543. Class.prototype.page = 1;
  544. //获得数据
  545. Class.prototype.pullData = function(curr){
  546. var that = this
  547. ,options = that.config
  548. ,request = options.request
  549. ,response = options.response
  550. ,sort = function(){
  551. if(typeof options.initSort === 'object'){
  552. that.sort(options.initSort.field, options.initSort.type);
  553. }
  554. };
  555. that.startTime = new Date().getTime(); //渲染开始时间
  556. if(options.url){ //Ajax请求
  557. var params = {};
  558. params[request.pageName] = curr;
  559. params[request.limitName] = options.limit;
  560. //参数
  561. var data = $.extend(params, options.where);
  562. if(options.contentType && options.contentType.indexOf("application/json") == 0){ //提交 json 格式
  563. data = JSON.stringify(data);
  564. }
  565. $.ajax({
  566. type: options.method || 'get'
  567. ,url: options.url
  568. ,contentType: options.contentType
  569. ,data: data
  570. ,dataType: 'json'
  571. ,headers: options.headers || {}
  572. ,success: function(res){
  573. //如果有数据解析的回调,则获得其返回的数据
  574. if(typeof options.parseData === 'function'){
  575. res = options.parseData(res) || res;
  576. }
  577. //检查数据格式是否符合规范
  578. if(res[response.statusName] != response.statusCode){
  579. that.renderForm();
  580. that.layMain.html('<div class="'+ NONE +'">'+ (
  581. res[response.msgName] ||
  582. ('返回的数据不符合规范,正确的成功状态码 ('+ response.statusName +') 应为:'+ response.statusCode)
  583. ) +'</div>');
  584. } else {
  585. that.renderData(res, curr, res[response.countName]), sort();
  586. options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时(接口请求+视图渲染)
  587. }
  588. that.setColsWidth();
  589. typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
  590. }
  591. ,error: function(e, m){
  592. that.layMain.html('<div class="'+ NONE +'">数据接口请求异常:'+ m +'</div>');
  593. that.renderForm();
  594. that.setColsWidth();
  595. }
  596. });
  597. } else if(options.data && options.data.constructor === Array){ //已知数据
  598. var res = {}
  599. ,startLimit = curr*options.limit - options.limit
  600. res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
  601. res[response.countName] = options.data.length;
  602. that.renderData(res, curr, options.data.length), sort();
  603. that.setColsWidth();
  604. typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
  605. }
  606. };
  607. //遍历表头
  608. Class.prototype.eachCols = function(callback){
  609. var that = this;
  610. table.eachCols(null, callback, that.config.cols);
  611. return that;
  612. };
  613. //数据渲染
  614. Class.prototype.renderData = function(res, curr, count, sort){
  615. var that = this
  616. ,options = that.config
  617. ,data = res[options.response.dataName] || []
  618. ,trs = []
  619. ,trs_fixed = []
  620. ,trs_fixed_r = []
  621. //渲染视图
  622. ,render = function(){ //后续性能提升的重点
  623. var thisCheckedRowIndex;
  624. if(!sort && that.sortKey){
  625. return that.sort(that.sortKey.field, that.sortKey.sort, true);
  626. }
  627. layui.each(data, function(i1, item1){
  628. var tds = [], tds_fixed = [], tds_fixed_r = []
  629. ,numbers = i1 + options.limit*(curr - 1) + 1; //序号
  630. if(item1.length === 0) return;
  631. if(!sort){
  632. item1[table.config.indexName] = i1;
  633. }
  634. that.eachCols(function(i3, item3){
  635. var field = item3.field || i3
  636. ,key = options.index + '-' + item3.key
  637. ,content = item1[field];
  638. if(content === undefined || content === null) content = '';
  639. if(item3.colGroup) return;
  640. //td内容
  641. var td = ['<td data-field="'+ field +'" data-key="'+ key +'" '+ function(){ //追加各种属性
  642. var attr = [];
  643. if(item3.edit) attr.push('data-edit="'+ item3.edit +'"'); //是否允许单元格编辑
  644. if(item3.align) attr.push('align="'+ item3.align +'"'); //对齐方式
  645. if(item3.templet) attr.push('data-content="'+ content +'"'); //自定义模板
  646. if(item3.toolbar) attr.push('data-off="true"'); //行工具列关闭单元格事件
  647. if(item3.event) attr.push('lay-event="'+ item3.event +'"'); //自定义事件
  648. if(item3.style) attr.push('style="'+ item3.style +'"'); //自定义样式
  649. if(item3.minWidth) attr.push('data-minwidth="'+ item3.minWidth +'"'); //单元格最小宽度
  650. return attr.join(' ');
  651. }() +' class="'+ function(){ //追加样式
  652. var classNames = [];
  653. if(item3.hide) classNames.push(HIDE); //插入隐藏列样式
  654. if(!item3.field) classNames.push('layui-table-col-special'); //插入特殊列样式
  655. return classNames.join(' ');
  656. }() +'">'
  657. ,'<div class="layui-table-cell laytable-cell-'+ function(){ //返回对应的CSS类标识
  658. return item3.type === 'normal' ? key
  659. : (key + ' laytable-cell-' + item3.type);
  660. }() +'">' + function(){
  661. var tplData = $.extend(true, {
  662. LAY_INDEX: numbers
  663. }, item1)
  664. ,checkName = table.config.checkName;
  665. //渲染不同风格的列
  666. switch(item3.type){
  667. case 'checkbox':
  668. return '<input type="checkbox" name="layTableCheckbox" lay-skin="primary" '+ function(){
  669. //如果是全选
  670. if(item3[checkName]){
  671. item1[checkName] = item3[checkName];
  672. return item3[checkName] ? 'checked' : '';
  673. }
  674. return tplData[checkName] ? 'checked' : '';
  675. }() +'>';
  676. break;
  677. case 'radio':
  678. if(tplData[checkName]){
  679. thisCheckedRowIndex = i1;
  680. }
  681. return '<input type="radio" name="layTableRadio_'+ options.index +'" '
  682. + (tplData[checkName] ? 'checked' : '') +' lay-type="layTableRadio">';
  683. break;
  684. case 'numbers':
  685. return numbers;
  686. break;
  687. };
  688. //解析工具列模板
  689. if(item3.toolbar){
  690. return laytpl($(item3.toolbar).html()||'').render(tplData);
  691. }
  692. return item3.templet ? function(){
  693. return typeof item3.templet === 'function'
  694. ? item3.templet(tplData)
  695. : laytpl($(item3.templet).html() || String(content)).render(tplData)
  696. }() : content;
  697. }()
  698. ,'</div></td>'].join('');
  699. tds.push(td);
  700. if(item3.fixed && item3.fixed !== 'right') tds_fixed.push(td);
  701. if(item3.fixed === 'right') tds_fixed_r.push(td);
  702. });
  703. trs.push('<tr data-index="'+ i1 +'">'+ tds.join('') + '</tr>');
  704. trs_fixed.push('<tr data-index="'+ i1 +'">'+ tds_fixed.join('') + '</tr>');
  705. trs_fixed_r.push('<tr data-index="'+ i1 +'">'+ tds_fixed_r.join('') + '</tr>');
  706. });
  707. that.layBody.scrollTop(0);
  708. that.layMain.find('.'+ NONE).remove();
  709. that.layMain.find('tbody').html(trs.join(''));
  710. that.layFixLeft.find('tbody').html(trs_fixed.join(''));
  711. that.layFixRight.find('tbody').html(trs_fixed_r.join(''));
  712. that.renderForm();
  713. typeof thisCheckedRowIndex === 'number' && that.setThisRowChecked(thisCheckedRowIndex);
  714. that.syncCheckAll();
  715. //滚动条补丁
  716. that.haveInit ? that.scrollPatch() : setTimeout(function(){
  717. that.scrollPatch();
  718. }, 50);
  719. that.haveInit = true;
  720. layer.close(that.tipsIndex);
  721. //同步表头父列的相关值
  722. options.HAS_SET_COLS_PATCH || that.setColsPatch();
  723. options.HAS_SET_COLS_PATCH = true;
  724. };
  725. that.key = options.id || options.index;
  726. table.cache[that.key] = data; //记录数据
  727. //显示隐藏分页栏
  728. that.layPage[(count == 0 || (data.length === 0 && curr == 1)) ? 'addClass' : 'removeClass'](HIDE);
  729. //排序
  730. if(sort){
  731. return render();
  732. }
  733. if(data.length === 0){
  734. that.renderForm();
  735. that.layFixed.remove();
  736. that.layMain.find('tbody').html('');
  737. that.layMain.find('.'+ NONE).remove();
  738. return that.layMain.append('<div class="'+ NONE +'">'+ options.text.none +'</div>');
  739. }
  740. render(); //渲染数据
  741. that.renderTotal(data); //数据合计
  742. //同步分页状态
  743. if(options.page){
  744. options.page = $.extend({
  745. elem: 'layui-table-page' + options.index
  746. ,count: count
  747. ,limit: options.limit
  748. ,limits: options.limits || [10,20,30,40,50,60,70,80,90]
  749. ,groups: 3
  750. ,layout: ['prev', 'page', 'next', 'skip', 'count', 'limit']
  751. ,prev: '<i class="layui-icon">&#xe603;</i>'
  752. ,next: '<i class="layui-icon">&#xe602;</i>'
  753. ,jump: function(obj, first){
  754. if(!first){
  755. //分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们
  756. //而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用)
  757. that.page = obj.curr; //更新页码
  758. options.limit = obj.limit; //更新每页条数
  759. that.loading();
  760. that.pullData(obj.curr);
  761. }
  762. }
  763. }, options.page);
  764. options.page.count = count; //更新总条数
  765. laypage.render(options.page);
  766. }
  767. };
  768. //数据合计行
  769. Class.prototype.renderTotal = function(data){
  770. var that = this
  771. ,options = that.config
  772. ,totalNums = {};
  773. if(!options.totalRow) return;
  774. layui.each(data, function(i1, item1){
  775. if(item1.length === 0) return;
  776. that.eachCols(function(i3, item3){
  777. var field = item3.field || i3
  778. ,content = item1[field];
  779. if(item3.totalRow){
  780. totalNums[field] = (totalNums[field] || 0) + (parseFloat(content) || 0);
  781. }
  782. });
  783. });
  784. var tds = [];
  785. that.eachCols(function(i3, item3){
  786. var field = item3.field || i3;
  787. //td内容
  788. var td = ['<td data-field="'+ field +'" data-key="'+ options.index + '-'+ item3.key +'" '+ function(){
  789. var attr = [];
  790. if(item3.align) attr.push('align="'+ item3.align +'"'); //对齐方式
  791. if(item3.style) attr.push('style="'+ item3.style +'"'); //自定义样式
  792. if(item3.minWidth) attr.push('data-minwidth="'+ item3.minWidth +'"'); //单元格最小宽度
  793. return attr.join(' ');
  794. }() +' class="'+ function(){ //追加样式
  795. var classNames = [];
  796. if(item3.hide) classNames.push(HIDE); //插入隐藏列样式
  797. if(!item3.field) classNames.push('layui-table-col-special'); //插入特殊列样式
  798. return classNames.join(' ');
  799. }() +'">'
  800. ,'<div class="layui-table-cell laytable-cell-'+ function(){ //返回对应的CSS类标识
  801. var str = (options.index + '-' + item3.key);
  802. return item3.type === 'normal' ? str
  803. : (str + ' laytable-cell-' + item3.type);
  804. }() +'">' + function(){
  805. var text = item3.totalRowText || '';
  806. return item3.totalRow ? (parseFloat(totalNums[field]).toFixed(2) || text) : text;
  807. }()
  808. ,'</div></td>'].join('');
  809. tds.push(td);
  810. });
  811. that.layTotal.find('tbody').html('<tr>' + tds.join('') + '</tr>');
  812. };
  813. //找到对应的列元素
  814. Class.prototype.getColElem = function(parent, key){
  815. var that = this
  816. ,options = that.config;
  817. return parent.eq(0).find('.laytable-cell-'+ (options.index + '-' + key) + ':eq(0)');
  818. };
  819. //渲染表单
  820. Class.prototype.renderForm = function(type){
  821. form.render(type, 'LAY-table-'+ this.index);
  822. };
  823. //标记当前行选中状态
  824. Class.prototype.setThisRowChecked = function(index){
  825. var that = this
  826. ,options = that.config
  827. ,ELEM_CLICK = 'layui-table-click'
  828. ,tr = that.layBody.find('tr[data-index="'+ index +'"]');
  829. tr.addClass(ELEM_CLICK).siblings('tr').removeClass(ELEM_CLICK);
  830. };
  831. //数据排序
  832. Class.prototype.sort = function(th, type, pull, formEvent){
  833. var that = this
  834. ,field
  835. ,res = {}
  836. ,options = that.config
  837. ,filter = options.elem.attr('lay-filter')
  838. ,data = table.cache[that.key], thisData;
  839. //字段匹配
  840. if(typeof th === 'string'){
  841. that.layHeader.find('th').each(function(i, item){
  842. var othis = $(this)
  843. ,_field = othis.data('field');
  844. if(_field === th){
  845. th = othis;
  846. field = _field;
  847. return false;
  848. }
  849. });
  850. }
  851. try {
  852. var field = field || th.data('field')
  853. ,key = th.data('key');
  854. //如果欲执行的排序已在状态中,则不执行渲染
  855. if(that.sortKey && !pull){
  856. if(field === that.sortKey.field && type === that.sortKey.sort){
  857. return;
  858. }
  859. }
  860. var elemSort = that.layHeader.find('th .laytable-cell-'+ key).find(ELEM_SORT);
  861. that.layHeader.find('th').find(ELEM_SORT).removeAttr('lay-sort'); //清除其它标题排序状态
  862. elemSort.attr('lay-sort', type || null);
  863. that.layFixed.find('th')
  864. } catch(e){
  865. return hint.error('Table modules: Did not match to field');
  866. }
  867. //记录排序索引和类型
  868. that.sortKey = {
  869. field: field
  870. ,sort: type
  871. };
  872. //默认为前端自动排序。如果否,则需自主排序(通常为服务端处理好排序)
  873. if(options.autoSort){
  874. if(type === 'asc'){ //升序
  875. thisData = layui.sort(data, field);
  876. } else if(type === 'desc'){ //降序
  877. thisData = layui.sort(data, field, true);
  878. } else { //清除排序
  879. thisData = layui.sort(data, table.config.indexName);
  880. delete that.sortKey;
  881. }
  882. }
  883. res[options.response.dataName] = thisData || data;
  884. that.renderData(res, that.page, that.count, true);
  885. if(formEvent){
  886. layui.event.call(th, MOD_NAME, 'sort('+ filter +')', {
  887. field: field
  888. ,type: type
  889. });
  890. }
  891. };
  892. //请求loading
  893. Class.prototype.loading = function(hide){
  894. var that = this
  895. ,options = that.config;
  896. if(options.loading){
  897. if(hide){
  898. that.layInit && that.layInit.remove();
  899. delete that.layInit;
  900. that.layBox.find(ELEM_INIT).remove()
  901. } else {
  902. that.layInit = $(['<div class="layui-table-init">'
  903. ,'<i class="layui-icon layui-icon-loading layui-icon"></i>'
  904. ,'</div>'].join(''));
  905. that.layBox.append(that.layInit);
  906. }
  907. }
  908. };
  909. //同步选中值状态
  910. Class.prototype.setCheckData = function(index, checked){
  911. var that = this
  912. ,options = that.config
  913. ,thisData = table.cache[that.key];
  914. if(!thisData[index]) return;
  915. if(thisData[index].constructor === Array) return;
  916. thisData[index][options.checkName] = checked;
  917. };
  918. //同步全选按钮状态
  919. Class.prototype.syncCheckAll = function(){
  920. var that = this
  921. ,options = that.config
  922. ,checkAllElem = that.layHeader.find('input[name="layTableCheckbox"]')
  923. ,syncColsCheck = function(checked){
  924. that.eachCols(function(i, item){
  925. if(item.type === 'checkbox'){
  926. item[options.checkName] = checked;
  927. }
  928. });
  929. return checked;
  930. };
  931. if(!checkAllElem[0]) return;
  932. if(table.checkStatus(that.key).isAll){
  933. if(!checkAllElem[0].checked){
  934. checkAllElem.prop('checked', true);
  935. that.renderForm('checkbox');
  936. }
  937. syncColsCheck(true);
  938. } else {
  939. if(checkAllElem[0].checked){
  940. checkAllElem.prop('checked', false);
  941. that.renderForm('checkbox');
  942. }
  943. syncColsCheck(false);
  944. }
  945. };
  946. //获取cssRule
  947. Class.prototype.getCssRule = function(key, callback){
  948. var that = this
  949. ,style = that.elem.find('style')[0]
  950. ,sheet = style.sheet || style.styleSheet || {}
  951. ,rules = sheet.cssRules || sheet.rules;
  952. layui.each(rules, function(i, item){
  953. if(item.selectorText === ('.laytable-cell-'+ key)){
  954. return callback(item), true;
  955. }
  956. });
  957. };
  958. //让表格铺满
  959. Class.prototype.fullSize = function(){
  960. var that = this
  961. ,options = that.config
  962. ,height = options.height, bodyHeight;
  963. if(that.fullHeightGap){
  964. height = _WIN.height() - that.fullHeightGap;
  965. if(height < 135) height = 135;
  966. that.elem.css('height', height);
  967. }
  968. if(!height) return;
  969. //减去列头区域的高度
  970. bodyHeight = parseFloat(height) - (that.layHeader.outerHeight() || 38); //此处的数字常量是为了防止容器处在隐藏区域无法获得高度的问题,暂时只对默认尺寸的表格做支持。
  971. //减去工具栏的高度
  972. if(options.toolbar){
  973. bodyHeight = bodyHeight - (that.layTool.outerHeight() || 50);
  974. }
  975. //减去统计朗的高度
  976. if(options.totalRow){
  977. bodyHeight = bodyHeight - (that.layTotal.outerHeight() || 40);
  978. }
  979. //减去分页栏的高度
  980. if(options.page){
  981. bodyHeight = bodyHeight - (that.layPage.outerHeight() || 41) - 2;
  982. }
  983. that.layMain.css('height', bodyHeight);
  984. };
  985. //获取滚动条宽度
  986. Class.prototype.getScrollWidth = function(elem){
  987. var width = 0;
  988. if(elem){
  989. width = elem.offsetWidth - elem.clientWidth;
  990. } else {
  991. elem = document.createElement('div');
  992. elem.style.width = '100px';
  993. elem.style.height = '100px';
  994. elem.style.overflowY = 'scroll';
  995. document.body.appendChild(elem);
  996. width = elem.offsetWidth - elem.clientWidth;
  997. document.body.removeChild(elem);
  998. }
  999. return width;
  1000. };
  1001. //滚动条补丁
  1002. Class.prototype.scrollPatch = function(){
  1003. var that = this
  1004. ,layMainTable = that.layMain.children('table')
  1005. ,scollWidth = that.layMain.width() - that.layMain.prop('clientWidth') //纵向滚动条宽度
  1006. ,scollHeight = that.layMain.height() - that.layMain.prop('clientHeight') //横向滚动条高度
  1007. ,getScrollWidth = that.getScrollWidth(that.layMain[0]) //获取主容器滚动条宽度,如果有的话
  1008. ,outWidth = layMainTable.outerWidth() - that.layMain.width() //表格内容器的超出宽度
  1009. //添加补丁
  1010. ,addPatch = function(elem){
  1011. if(scollWidth && scollHeight){
  1012. elem = elem.eq(0);
  1013. if(!elem.find('.layui-table-patch')[0]){
  1014. var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
  1015. patchElem.find('div').css({
  1016. width: scollWidth
  1017. });
  1018. elem.find('tr').append(patchElem);
  1019. }
  1020. } else {
  1021. elem.find('.layui-table-patch').remove();
  1022. }
  1023. }
  1024. addPatch(that.layHeader);
  1025. addPatch(that.layTotal);
  1026. //固定列区域高度
  1027. var mainHeight = that.layMain.height()
  1028. ,fixHeight = mainHeight - scollHeight;
  1029. that.layFixed.find(ELEM_BODY).css('height', layMainTable.height() >= fixHeight ? fixHeight : 'auto');
  1030. //表格宽度小于容器宽度时,隐藏固定列
  1031. that.layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
  1032. //操作栏
  1033. that.layFixRight.css('right', scollWidth - 1);
  1034. };
  1035. //事件处理
  1036. Class.prototype.events = function(){
  1037. var that = this
  1038. ,options = that.config
  1039. ,_BODY = $('body')
  1040. ,dict = {}
  1041. ,th = that.layHeader.find('th')
  1042. ,resizing
  1043. ,ELEM_CELL = '.layui-table-cell'
  1044. ,filter = options.elem.attr('lay-filter');
  1045. //工具栏操作事件
  1046. that.layTool.on('click', '*[lay-event]', function(e){
  1047. var othis = $(this)
  1048. ,events = othis.attr('lay-event')
  1049. ,openPanel = function(sets){
  1050. var list = $(sets.list)
  1051. ,panel = $('<ul class="layui-table-tool-panel"></ul>');
  1052. panel.html(list);
  1053. //限制最大高度
  1054. if(options.height){
  1055. panel.css('max-height', options.height - (that.layTool.outerHeight() || 50));
  1056. }
  1057. //插入元素
  1058. othis.find('.layui-table-tool-panel')[0] || othis.append(panel);
  1059. that.renderForm();
  1060. panel.on('click', function(e){
  1061. layui.stope(e);
  1062. });
  1063. sets.done && sets.done(panel, list)
  1064. };
  1065. layui.stope(e);
  1066. _DOC.trigger('table.tool.panel.remove');
  1067. layer.close(that.tipsIndex);
  1068. switch(events){
  1069. case 'LAYTABLE_COLS': //筛选列
  1070. openPanel({
  1071. list: function(){
  1072. var lis = [];
  1073. that.eachCols(function(i, item){
  1074. if(item.field && item.type == 'normal'){
  1075. lis.push('<li><input type="checkbox" name="'+ item.field +'" data-key="'+ item.key +'" data-parentkey="'+ (item.parentKey||'') +'" lay-skin="primary" '+ (item.hide ? '' : 'checked') +' title="'+ (item.title || item.field) +'" lay-filter="LAY_TABLE_TOOL_COLS"></li>');
  1076. }
  1077. });
  1078. return lis.join('');
  1079. }()
  1080. ,done: function(){
  1081. form.on('checkbox(LAY_TABLE_TOOL_COLS)', function(obj){
  1082. var othis = $(obj.elem)
  1083. ,checked = this.checked
  1084. ,key = othis.data('key')
  1085. ,parentKey = othis.data('parentkey');
  1086. layui.each(options.cols, function(i1, item1){
  1087. layui.each(item1, function(i2, item2){
  1088. if(i1+ '-'+ i2 === key){
  1089. var hide = item2.hide;
  1090. //同步勾选列的 hide 值和隐藏样式
  1091. item2.hide = !checked;
  1092. that.elem.find('*[data-key="'+ options.index +'-'+ key +'"]')
  1093. [checked ? 'removeClass' : 'addClass'](HIDE);
  1094. //根据列的显示隐藏,同步多级表头的父级相关属性值
  1095. if(hide != item2.hide){
  1096. that.setParentCol(!checked, parentKey);
  1097. }
  1098. //重新适配尺寸
  1099. that.resize();
  1100. }
  1101. });
  1102. });
  1103. });
  1104. }
  1105. });
  1106. break;
  1107. case 'LAYTABLE_EXPORT': //导出
  1108. if(device.ie){
  1109. layer.tips('导出功能不支持 IE,请用 Chrome 等高级浏览器导出', this, {
  1110. tips: 3
  1111. })
  1112. } else {
  1113. openPanel({
  1114. list: function(){
  1115. return [
  1116. '<li data-type="csv">导出到 Csv 文件</li>'
  1117. ,'<li data-type="xls">导出到 Excel 文件</li>'
  1118. ].join('')
  1119. }()
  1120. ,done: function(panel, list){
  1121. list.on('click', function(){
  1122. var type = $(this).data('type')
  1123. table.exportFile(options.id, null, type);
  1124. });
  1125. }
  1126. });
  1127. }
  1128. break;
  1129. case 'LAYTABLE_PRINT': //打印
  1130. var printWin = window.open('打印窗口', '_blank')
  1131. ,style = ['<style>'
  1132. ,'body{font-size: 12px; color: #666;}'
  1133. ,'table{width: 100%; border-collapse: collapse; border-spacing: 0;}'
  1134. ,'th,td{line-height: 20px; padding: 9px 15px; border: 1px solid #ccc; text-align: left; font-size: 12px; color: #666;}'
  1135. ,'a{color: #666; text-decoration:none;}'
  1136. ,'*.layui-hide{display: none}'
  1137. ,'</style>'].join('')
  1138. ,html = $(that.layHeader.html());
  1139. html.append(that.layMain.find('table').html());
  1140. html.find('th.layui-table-patch').remove();
  1141. html.find('.layui-table-col-special').remove();
  1142. printWin.document.write(style + html.prop('outerHTML'));
  1143. printWin.document.close();
  1144. printWin.print();
  1145. printWin.close();
  1146. break;
  1147. }
  1148. layui.event.call(this, MOD_NAME, 'toolbar('+ filter +')', $.extend({
  1149. event: events
  1150. ,config: options
  1151. },{}));
  1152. });
  1153. //拖拽调整宽度
  1154. th.on('mousemove', function(e){
  1155. var othis = $(this)
  1156. ,oLeft = othis.offset().left
  1157. ,pLeft = e.clientX - oLeft;
  1158. if(othis.data('unresize') || dict.resizeStart){
  1159. return;
  1160. }
  1161. dict.allowResize = othis.width() - pLeft <= 10; //是否处于拖拽允许区域
  1162. _BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
  1163. }).on('mouseleave', function(){
  1164. var othis = $(this);
  1165. if(dict.resizeStart) return;
  1166. _BODY.css('cursor', '');
  1167. }).on('mousedown', function(e){
  1168. var othis = $(this);
  1169. if(dict.allowResize){
  1170. var key = othis.data('key');
  1171. e.preventDefault();
  1172. dict.resizeStart = true; //开始拖拽
  1173. dict.offset = [e.clientX, e.clientY]; //记录初始坐标
  1174. that.getCssRule(key, function(item){
  1175. var width = item.style.width || othis.outerWidth();
  1176. dict.rule = item;
  1177. dict.ruleWidth = parseFloat(width);
  1178. dict.minWidth = othis.data('minwidth') || options.cellMinWidth;
  1179. });
  1180. }
  1181. });
  1182. //拖拽中
  1183. _DOC.on('mousemove', function(e){
  1184. if(dict.resizeStart){
  1185. e.preventDefault();
  1186. if(dict.rule){
  1187. var setWidth = dict.ruleWidth + e.clientX - dict.offset[0];
  1188. if(setWidth < dict.minWidth) setWidth = dict.minWidth;
  1189. dict.rule.style.width = setWidth + 'px';
  1190. layer.close(that.tipsIndex);
  1191. }
  1192. resizing = 1
  1193. }
  1194. }).on('mouseup', function(e){
  1195. if(dict.resizeStart){
  1196. dict = {};
  1197. _BODY.css('cursor', '');
  1198. that.scrollPatch();
  1199. }
  1200. if(resizing === 2){
  1201. resizing = null;
  1202. }
  1203. });
  1204. //排序
  1205. th.on('click', function(e){
  1206. var othis = $(this)
  1207. ,elemSort = othis.find(ELEM_SORT)
  1208. ,nowType = elemSort.attr('lay-sort')
  1209. ,type;
  1210. if(!elemSort[0] || resizing === 1) return resizing = 2;
  1211. if(nowType === 'asc'){
  1212. type = 'desc';
  1213. } else if(nowType === 'desc'){
  1214. type = null;
  1215. } else {
  1216. type = 'asc';
  1217. }
  1218. that.sort(othis, type, null, true);
  1219. }).find(ELEM_SORT+' .layui-edge ').on('click', function(e){
  1220. var othis = $(this)
  1221. ,index = othis.index()
  1222. ,field = othis.parents('th').eq(0).data('field')
  1223. layui.stope(e);
  1224. if(index === 0){
  1225. that.sort(field, 'asc', null, true);
  1226. } else {
  1227. that.sort(field, 'desc', null, true);
  1228. }
  1229. });
  1230. //数据行中的事件监听返回的公共对象成员
  1231. var commonMember = function(sets){
  1232. var othis = $(this)
  1233. ,index = othis.parents('tr').eq(0).data('index')
  1234. ,tr = that.layBody.find('tr[data-index="'+ index +'"]')
  1235. ,data = table.cache[that.key][index];
  1236. return $.extend({
  1237. tr: tr //行元素
  1238. ,data: table.clearCacheKey(data) //当前行数据
  1239. ,del: function(){ //删除行数据
  1240. table.cache[that.key][index] = [];
  1241. tr.remove();
  1242. that.scrollPatch();
  1243. }
  1244. ,update: function(fields){ //修改行数据
  1245. fields = fields || {};
  1246. layui.each(fields, function(key, value){
  1247. if(key in data){
  1248. var templet, td = tr.children('td[data-field="'+ key +'"]');
  1249. data[key] = value;
  1250. that.eachCols(function(i, item2){
  1251. if(item2.field == key && item2.templet){
  1252. templet = item2.templet;
  1253. }
  1254. });
  1255. td.children(ELEM_CELL).html(function(){
  1256. return templet ? function(){
  1257. return typeof templet === 'function'
  1258. ? templet(data)
  1259. : laytpl($(templet).html() || value).render(data)
  1260. }() : value;
  1261. }());
  1262. td.data('content', value);
  1263. }
  1264. });
  1265. }
  1266. }, sets);
  1267. };
  1268. //复选框选择
  1269. that.elem.on('click', 'input[name="layTableCheckbox"]+', function(){ //替代元素的 click 事件
  1270. var checkbox = $(this).prev()
  1271. ,childs = that.layBody.find('input[name="layTableCheckbox"]')
  1272. ,index = checkbox.parents('tr').eq(0).data('index')
  1273. ,checked = checkbox[0].checked
  1274. ,isAll = checkbox.attr('lay-filter') === 'layTableAllChoose';
  1275. //全选
  1276. if(isAll){
  1277. childs.each(function(i, item){
  1278. item.checked = checked;
  1279. that.setCheckData(i, checked);
  1280. });
  1281. that.syncCheckAll();
  1282. that.renderForm('checkbox');
  1283. } else {
  1284. that.setCheckData(index, checked);
  1285. that.syncCheckAll();
  1286. }
  1287. layui.event.call(checkbox[0], MOD_NAME, 'checkbox('+ filter +')', commonMember.call(checkbox[0], {
  1288. checked: checked
  1289. ,type: isAll ? 'all' : 'one'
  1290. }));
  1291. });
  1292. //单选框选择
  1293. that.elem.on('click', 'input[lay-type="layTableRadio"]+', function(){
  1294. var radio = $(this).prev()
  1295. ,checked = radio[0].checked
  1296. ,thisData = table.cache[that.key]
  1297. ,index = radio.parents('tr').eq(0).data('index');
  1298. //重置数据单选属性
  1299. layui.each(thisData, function(i, item){
  1300. if(index === i){
  1301. item.LAY_CHECKED = true;
  1302. } else {
  1303. delete item.LAY_CHECKED;
  1304. }
  1305. });
  1306. that.setThisRowChecked(index);
  1307. layui.event.call(this, MOD_NAME, 'radio('+ filter +')', commonMember.call(this, {
  1308. checked: checked
  1309. }));
  1310. });
  1311. //行事件
  1312. that.layBody.on('mouseenter', 'tr', function(){ //鼠标移入行
  1313. var othis = $(this)
  1314. ,index = othis.index();
  1315. that.layBody.find('tr:eq('+ index +')').addClass(ELEM_HOVER)
  1316. }).on('mouseleave', 'tr', function(){ //鼠标移出行
  1317. var othis = $(this)
  1318. ,index = othis.index();
  1319. that.layBody.find('tr:eq('+ index +')').removeClass(ELEM_HOVER)
  1320. }).on('click', 'tr', function(){ //单击行
  1321. setRowEvent.call(this, 'row');
  1322. }).on('dblclick', 'tr', function(){ //双击行
  1323. setRowEvent.call(this, 'rowDouble');
  1324. });
  1325. //创建行单击、双击事件监听
  1326. var setRowEvent = function(eventType){
  1327. var othis = $(this);
  1328. layui.event.call(this,
  1329. MOD_NAME, eventType + '('+ filter +')'
  1330. ,commonMember.call(othis.children('td')[0])
  1331. );
  1332. };
  1333. let inputBlur = function(e){
  1334. var templet
  1335. ,othis = $(this)
  1336. ,field = othis.parent().data('field')
  1337. ,index = othis.parents('tr').eq(0).data('index')
  1338. ,data = table.cache[that.key][index];
  1339. that.eachCols(function(i, item){
  1340. if(item.field == field && item.templet){
  1341. templet = item.templet;
  1342. }
  1343. });
  1344. othis.siblings(ELEM_CELL).html(function(value){
  1345. return templet ? function(){
  1346. return typeof templet === 'function'
  1347. ? templet(data)
  1348. : laytpl($(templet).html() || this.value || e.value).render(data)
  1349. }() : value;
  1350. }(this.value));
  1351. othis.parent().data('content', this.value || e.value);
  1352. e.blurRemove && othis.remove();
  1353. othis.attr('id') || othis.remove();
  1354. };
  1355. let inputChenge = function(e){
  1356. var othis = $(this)
  1357. ,value = this.value || e.value
  1358. ,field = othis.parent().data('field')
  1359. ,index = othis.parents('tr').eq(0).data('index')
  1360. ,data = table.cache[that.key][index];
  1361. data[field] = value; //更新缓存中的值
  1362. layui.event.call(this, MOD_NAME, 'edit('+ filter +')', commonMember.call(this, {
  1363. value: value
  1364. ,field: field
  1365. }));
  1366. };
  1367. //单元格编辑
  1368. that.layBody.on('change', '.'+ELEM_EDIT, inputChenge).on('blur', '.'+ELEM_EDIT, inputBlur);
  1369. var input = $('<input class="layui-input '+ ELEM_EDIT +'">');
  1370. //单元格单击事件
  1371. that.layBody.on('click', 'td', function(e){
  1372. var othis = $(this)
  1373. ,field = othis.data('field')
  1374. ,editType = othis.data('edit')
  1375. ,elemCell = othis.children(ELEM_CELL);
  1376. if(othis.data('off')) return; //不触发事件
  1377. //显示编辑表单
  1378. if(editType){
  1379. input.remove();
  1380. input = $('<input class="layui-input '+ ELEM_EDIT +'">');
  1381. input[0].value = othis.data('content') || elemCell.text();
  1382. othis.find('.'+ELEM_EDIT)[0] || othis.append(input);
  1383. if(editType == 'time'){
  1384. let _id = that.config.id+othis.data('key');
  1385. input.attr('id',_id);
  1386. laydate.render({
  1387. elem: '#'+_id,
  1388. type: 'datetime',
  1389. done:function(value, date, endDate){
  1390. input['inputBlur'] = inputBlur;
  1391. input['inputChenge'] = inputChenge;
  1392. input['inputChenge']({
  1393. value:value
  1394. });
  1395. input['inputBlur']({
  1396. blurRemove:true,
  1397. value:value
  1398. });
  1399. elemCell.text(value);
  1400. }
  1401. });
  1402. }
  1403. input.focus();
  1404. layui.stope(e);
  1405. return;
  1406. }
  1407. }).on('mouseenter', 'td', function(){
  1408. gridExpand.call(this)
  1409. }).on('mouseleave', 'td', function(){
  1410. gridExpand.call(this, 'hide');
  1411. });
  1412. //单元格展开图标
  1413. var ELEM_GRID = 'layui-table-grid', ELEM_GRID_DOWN = 'layui-table-grid-down', ELEM_GRID_PANEL = 'layui-table-grid-panel'
  1414. ,gridExpand = function(hide){
  1415. var othis = $(this)
  1416. ,elemCell = othis.children(ELEM_CELL);
  1417. if(hide){
  1418. othis.find('.layui-table-grid-down').remove();
  1419. } else if(elemCell.prop('scrollWidth') > elemCell.outerWidth()){
  1420. if(elemCell.find('.'+ ELEM_GRID_DOWN)[0]) return;
  1421. othis.append('<div class="'+ ELEM_GRID_DOWN +'"><i class="layui-icon layui-icon-down"></i></div>');
  1422. }
  1423. };
  1424. //单元格展开事件
  1425. that.layBody.on('click', '.'+ ELEM_GRID_DOWN, function(e){
  1426. var othis = $(this)
  1427. ,td = othis.parent()
  1428. ,elemCell = td.children(ELEM_CELL);
  1429. that.tipsIndex = layer.tips([
  1430. '<div class="layui-table-tips-main" style="margin-top: -'+ (elemCell.height() + 16) +'px;'+ function(){
  1431. if(options.size === 'sm'){
  1432. return 'padding: 4px 15px; font-size: 12px;';
  1433. }
  1434. if(options.size === 'lg'){
  1435. return 'padding: 14px 15px;';
  1436. }
  1437. return '';
  1438. }() +'">'
  1439. ,elemCell.html()
  1440. ,'</div>'
  1441. ,'<i class="layui-icon layui-table-tips-c layui-icon-close"></i>'
  1442. ].join(''), elemCell[0], {
  1443. tips: [3, '']
  1444. ,time: -1
  1445. ,anim: -1
  1446. ,maxWidth: (device.ios || device.android) ? 300 : that.elem.width()/2
  1447. ,isOutAnim: false
  1448. ,skin: 'layui-table-tips'
  1449. ,success: function(layero, index){
  1450. layero.find('.layui-table-tips-c').on('click', function(){
  1451. layer.close(index);
  1452. });
  1453. }
  1454. });
  1455. layui.stope(e);
  1456. });
  1457. //行工具条操作事件
  1458. that.layBody.on('click', '*[lay-event]', function(){
  1459. var othis = $(this)
  1460. ,index = othis.parents('tr').eq(0).data('index');
  1461. layui.event.call(this, MOD_NAME, 'tool('+ filter +')', commonMember.call(this, {
  1462. event: othis.attr('lay-event')
  1463. }));
  1464. that.setThisRowChecked(index);
  1465. });
  1466. //同步滚动条
  1467. that.layMain.on('scroll', function(){
  1468. var othis = $(this)
  1469. ,scrollLeft = othis.scrollLeft()
  1470. ,scrollTop = othis.scrollTop();
  1471. that.layHeader.scrollLeft(scrollLeft);
  1472. that.layTotal.scrollLeft(scrollLeft);
  1473. that.layFixed.find(ELEM_BODY).scrollTop(scrollTop);
  1474. layer.close(that.tipsIndex);
  1475. });
  1476. //全局点击
  1477. _DOC.on('click', function(){
  1478. _DOC.trigger('table.remove.tool.panel');
  1479. });
  1480. //工具面板移除事件
  1481. _DOC.on('table.remove.tool.panel', function(){
  1482. $('.layui-table-tool-panel').remove();
  1483. });
  1484. //自适应
  1485. _WIN.on('resize', function(){
  1486. that.resize();
  1487. });
  1488. };
  1489. //初始化
  1490. table.init = function(filter, settings){
  1491. settings = settings || {};
  1492. var that = this
  1493. ,elemTable = filter ? $('table[lay-filter="'+ filter +'"]') : $(ELEM + '[lay-data]')
  1494. ,errorTips = 'Table element property lay-data configuration item has a syntax error: ';
  1495. //遍历数据表格
  1496. elemTable.each(function(){
  1497. var othis = $(this), tableData = othis.attr('lay-data');
  1498. try{
  1499. tableData = new Function('return '+ tableData)();
  1500. } catch(e){
  1501. hint.error(errorTips + tableData)
  1502. }
  1503. var cols = [], options = $.extend({
  1504. elem: this
  1505. ,cols: []
  1506. ,data: []
  1507. ,skin: othis.attr('lay-skin') //风格
  1508. ,size: othis.attr('lay-size') //尺寸
  1509. ,even: typeof othis.attr('lay-even') === 'string' //偶数行背景
  1510. }, table.config, settings, tableData);
  1511. filter && othis.hide();
  1512. //获取表头数据
  1513. othis.find('thead>tr').each(function(i){
  1514. options.cols[i] = [];
  1515. $(this).children().each(function(ii){
  1516. var th = $(this), itemData = th.attr('lay-data');
  1517. try{
  1518. itemData = new Function('return '+ itemData)();
  1519. } catch(e){
  1520. return hint.error(errorTips + itemData)
  1521. }
  1522. var row = $.extend({
  1523. title: th.text()
  1524. ,colspan: th.attr('colspan') || 0 //列单元格
  1525. ,rowspan: th.attr('rowspan') || 0 //行单元格
  1526. }, itemData);
  1527. if(row.colspan < 2) cols.push(row);
  1528. options.cols[i].push(row);
  1529. });
  1530. });
  1531. //获取表体数据
  1532. othis.find('tbody>tr').each(function(i1){
  1533. var tr = $(this), row = {};
  1534. //如果定义了字段名
  1535. tr.children('td').each(function(i2, item2){
  1536. var td = $(this)
  1537. ,field = td.data('field');
  1538. if(field){
  1539. return row[field] = td.html();
  1540. }
  1541. });
  1542. //如果未定义字段名
  1543. layui.each(cols, function(i3, item3){
  1544. var td = tr.children('td').eq(i3);
  1545. row[item3.field] = td.html();
  1546. });
  1547. options.data[i1] = row;
  1548. });
  1549. table.render(options);
  1550. });
  1551. return that;
  1552. };
  1553. //记录所有实例
  1554. thisTable.that = {}; //记录所有实例对象
  1555. thisTable.config = {}; //记录所有实例配置项
  1556. //遍历表头
  1557. table.eachCols = function(id, callback, cols){
  1558. var config = thisTable.config[id] || {}
  1559. ,arrs = [], index = 0;
  1560. cols = $.extend(true, [], cols || config.cols);
  1561. //重新整理表头结构
  1562. layui.each(cols, function(i1, item1){
  1563. layui.each(item1, function(i2, item2){
  1564. //如果是组合列,则捕获对应的子列
  1565. if(item2.colGroup){
  1566. var childIndex = 0;
  1567. index++
  1568. item2.CHILD_COLS = [];
  1569. layui.each(cols[i1 + 1], function(i22, item22){
  1570. //如果子列已经被标注为{PARENT_COL_INDEX},或者子列累计 colspan 数等于父列定义的 colspan,则跳出当前子列循环
  1571. if(item22.PARENT_COL_INDEX || (childIndex > 1 && childIndex == item2.colspan)) return;
  1572. item22.PARENT_COL_INDEX = index;
  1573. item2.CHILD_COLS.push(item22);
  1574. childIndex = childIndex + parseInt(item22.colspan > 1 ? item22.colspan : 1);
  1575. });
  1576. }
  1577. if(item2.PARENT_COL_INDEX) return; //如果是子列,则不进行追加,因为已经存储在父列中
  1578. arrs.push(item2)
  1579. });
  1580. });
  1581. //重新遍历列,如果有子列,则进入递归
  1582. var eachArrs = function(obj){
  1583. layui.each(obj || arrs, function(i, item){
  1584. if(item.CHILD_COLS) return eachArrs(item.CHILD_COLS);
  1585. typeof callback === 'function' && callback(i, item);
  1586. });
  1587. };
  1588. eachArrs();
  1589. };
  1590. //表格选中状态
  1591. table.checkStatus = function(id){
  1592. var nums = 0
  1593. ,invalidNum = 0
  1594. ,arr = []
  1595. ,data = table.cache[id] || [];
  1596. //计算全选个数
  1597. layui.each(data, function(i, item){
  1598. if(item.constructor === Array){
  1599. invalidNum++; //无效数据,或已删除的
  1600. return;
  1601. }
  1602. if(item[table.config.checkName]){
  1603. nums++;
  1604. arr.push(table.clearCacheKey(item));
  1605. }
  1606. });
  1607. return {
  1608. data: arr //选中的数据
  1609. ,isAll: data.length ? (nums === (data.length - invalidNum)) : false //是否全选
  1610. };
  1611. };
  1612. //表格导出
  1613. table.exportFile = function(id, data, type){
  1614. data = data || table.clearCacheKey(table.cache[id]);
  1615. type = type || 'csv';
  1616. var config = thisTable.config[id] || {}
  1617. ,textType = ({
  1618. csv: 'text/csv'
  1619. ,xls: 'application/vnd.ms-excel'
  1620. })[type]
  1621. ,alink = document.createElement("a");
  1622. if(device.ie) return hint.error('IE_NOT_SUPPORT_EXPORTS');
  1623. alink.href = 'data:'+ textType +';charset=utf-8,\ufeff'+ encodeURIComponent(function(){
  1624. var dataTitle = [], dataMain = [];
  1625. layui.each(data, function(i1, item1){
  1626. var vals = [];
  1627. if(typeof id === 'object'){ //ID直接为表头数据
  1628. layui.each(id, function(i, item){
  1629. i1 == 0 && dataTitle.push(item || '');
  1630. });
  1631. layui.each(table.clearCacheKey(item1), function(i2, item2){
  1632. vals.push(item2);
  1633. });
  1634. } else {
  1635. table.eachCols(id, function(i3, item3){
  1636. if(item3.field && item3.type == 'normal' && !item3.hide){
  1637. i1 == 0 && dataTitle.push(item3.title || '');
  1638. vals.push(item1[item3.field]);
  1639. }
  1640. });
  1641. }
  1642. dataMain.push(vals.join(','))
  1643. });
  1644. return dataTitle.join(',') + '\r\n' + dataMain.join('\r\n');
  1645. }());
  1646. alink.download = (config.title || 'table_'+ (config.index || '')) + '.' + type;
  1647. document.body.appendChild(alink);
  1648. alink.click();
  1649. document.body.removeChild(alink);
  1650. };
  1651. //重置表格尺寸结构
  1652. table.resize = function(id){
  1653. //如果指定表格唯一 id,则只执行该 id 对应的表格实例
  1654. if(id){
  1655. var config = getThisTableConfig(id); //获取当前实例配置项
  1656. if(!config) return;
  1657. thisTable.that[id].resize();
  1658. } else { //否则重置所有表格实例尺寸
  1659. layui.each(thisTable.that, function(){
  1660. this.resize();
  1661. });
  1662. }
  1663. };
  1664. //表格重载
  1665. table.reload = function(id, options){
  1666. options = options || {};
  1667. var config = getThisTableConfig(id); //获取当前实例配置项
  1668. if(!config) return;
  1669. if(options.data && options.data.constructor === Array) delete config.data;
  1670. return table.render($.extend(true, {}, config, options));
  1671. };
  1672. //核心入口
  1673. table.render = function(options){
  1674. var inst = new Class(options);
  1675. return thisTable.call(inst);
  1676. };
  1677. //清除临时Key
  1678. table.clearCacheKey = function(data){
  1679. data = $.extend({}, data);
  1680. delete data[table.config.checkName];
  1681. delete data[table.config.indexName];
  1682. return data;
  1683. };
  1684. //自动完成渲染
  1685. table.init();
  1686. exports(MOD_NAME, table);
  1687. });