table.js 63 KB

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