table.js 64 KB

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