dltable.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  1. /**
  2. @Name:dl table 操作
  3. @Author:lrd
  4. */
  5. layui.define(['laytpl', 'laypage', 'layer', 'form'], function(exports){
  6. "use strict";
  7. var $ = layui.$
  8. ,laytpl = layui.laytpl
  9. ,laypage = layui.laypage
  10. ,layer = layui.layer
  11. ,form = layui.form
  12. ,hint = layui.hint()
  13. ,device = layui.device()
  14. //外部接口
  15. ,table = {
  16. claObj:{}//全部的class对象map
  17. ,obj:{}//额外保存的数据
  18. ,config: {//全局配置项
  19. checkName: 'LAY_CHECKED' //是否选中状态的字段名
  20. ,indexName: 'LAY_TABLE_INDEX' //下标索引名
  21. }
  22. /**
  23. * 缓存数据
  24. *
  25. * 结构图示
  26. * cache{} 缓存(对象)
  27. * key['data']{} 全部数据缓存(对象)
  28. * key[list][] 列表数据对象(数组)
  29. * key[map]{} 列表数据Map对象(Map)
  30. * key[treeList][] 树状结构的对象(数组)
  31. * key['cla']{} 全部已初始化过的Calss对象类(注意渲染是异步执行)
  32. * key['claIds'][] 全部已经吊用过初始化方法的表格类
  33. * key[claObjs]{key[tableId]} 全部已经初始化好的cla对象
  34. *
  35. */
  36. ,cache: {
  37. tableId:{
  38. data:{
  39. list:[]//列表数据
  40. ,map:{}//列表数据以idField或唯一值作为key的Map数据
  41. ,treeList:[]//树状数据
  42. }
  43. }
  44. ,cla:{
  45. claIds:{
  46. tableId:true
  47. }
  48. ,claObjs:{
  49. tableId:{}
  50. }
  51. }
  52. ,selectcode:{//数据字典缓存
  53. demokey:[
  54. {
  55. key:{value:''}
  56. }
  57. ]
  58. }
  59. }
  60. ,index: layui.table ? (layui.table.index + 10000) : 0
  61. /**
  62. * 设置全局项
  63. * @param options
  64. * @return {table}
  65. */
  66. ,set: function(options){
  67. var that = this;
  68. that.config = $.extend({}, that.config, options);
  69. return that;
  70. }
  71. /**
  72. * 事件监听
  73. * @param events
  74. * @param callback
  75. * @return {*}
  76. */
  77. ,on: function(events, callback){
  78. return layui.onevent.call(this, MOD_NAME, events, callback);
  79. }
  80. ,getClass:function (tableId) {
  81. return table.cache.cla.claObjs[tableId];;
  82. }
  83. ,pushClass:function (tableId,that) {
  84. table.cache.cla.claObjs[tableId]=that;
  85. }
  86. ,isCalss:function (tableId) {
  87. var ids=this.cache.cla.claIds||{};
  88. return ids.hasOwnProperty(tableId)||false;
  89. }
  90. ,isClassYes:function (tableId) {
  91. var ids=this.cache.cla.claIds||{};
  92. return ids[tableId]||false;
  93. }
  94. ,pushClassIds:function (tableId,is) {
  95. this.cache.cla.claIds[tableId]=is;
  96. }
  97. ,setObj:function (tableId,key,o) {
  98. if(!this.obj[tableId])this.obj[tableId]={};
  99. this.obj[tableId][key]=o;
  100. }
  101. ,getObj:function (tableId, key) {
  102. return this.obj[tableId]?this.obj[tableId][key]:null;
  103. }
  104. /**
  105. * 获取列表数据
  106. */
  107. ,getDataList:function (tableId) {
  108. if(table.cache[tableId]){
  109. return table.cache[tableId].data.list;
  110. }
  111. return [];
  112. }
  113. /**
  114. * 设置列表数据
  115. */
  116. ,setDataList:function (tableId, list) {
  117. if(!table.cache[tableId])table.cache[tableId]={};
  118. if(!table.cache[tableId].data)table.cache[tableId].data={};
  119. if(!table.cache[tableId].data.list)table.cache[tableId].data.list=[];
  120. table.cache[tableId].data.list=list;
  121. }
  122. /**
  123. * 获取列表数据
  124. */
  125. ,getDataMap:function (tableId) {
  126. if(table.cache[tableId]){
  127. return table.cache[tableId].data.map;
  128. }
  129. return {};
  130. }
  131. /**
  132. * 设置列表数据
  133. */
  134. ,setDataMap:function (tableId, map) {
  135. if(!table.cache[tableId])table.cache[tableId]={};
  136. if(!table.cache[tableId].data)table.cache[tableId].data={};
  137. if(!table.cache[tableId].data.map)table.cache[tableId].data.map={};
  138. table.cache[tableId].data.map=map;
  139. }
  140. /**
  141. * 获取树状数据
  142. */
  143. ,getDataTreeList:function (tableId) {
  144. if(table.cache[tableId]){
  145. return table.cache[tableId].data.treeList;
  146. }
  147. return [];
  148. }
  149. /**
  150. * 设置树状数据
  151. */
  152. ,setDataTreeList:function (tableId, treeList) {
  153. if(!table.cache[tableId])table.cache[tableId]={};
  154. if(!table.cache[tableId].data)table.cache[tableId].data={};
  155. if(!table.cache[tableId].data.treeList)table.cache[tableId].data.treeList={};
  156. table.cache[tableId].data.treeList=treeList;
  157. }
  158. /**
  159. * 初始化
  160. * @param filter
  161. * @param settings
  162. * @return {table}
  163. */
  164. ,init:function (filter, settings) {
  165. settings = settings || {};
  166. var that = this
  167. ,elemTable = filter ? $('table[lay-filter="'+ filter +'"]') : $(ELEM + '[lay-data]')
  168. ,errorTips = 'Table element property lay-data configuration item has a syntax error: ';
  169. //遍历数据表格
  170. elemTable.each(function(){
  171. var othis = $(this), tableData = othis.attr('lay-data');
  172. try{
  173. tableData = new Function('return '+ tableData)();
  174. } catch(e){
  175. hint.error(errorTips + tableData)
  176. }
  177. var cols = [], options = $.extend({
  178. elem: this
  179. ,cols: []
  180. ,data: []
  181. ,skin: othis.attr('lay-skin') //风格
  182. ,size: othis.attr('lay-size') //尺寸
  183. ,even: typeof othis.attr('lay-even') === 'string' //偶数行背景
  184. }, table.config, settings, tableData);
  185. filter && othis.hide();
  186. //获取表头数据
  187. othis.find('thead>tr').each(function(i){
  188. options.cols[i] = [];
  189. $(this).children().each(function(ii){
  190. var th = $(this), itemData = th.attr('lay-data');
  191. try{
  192. itemData = new Function('return '+ itemData)();
  193. } catch(e){
  194. return hint.error(errorTips + itemData)
  195. }
  196. var row = $.extend({
  197. title: th.text()
  198. ,colspan: th.attr('colspan') || 0 //列单元格
  199. ,rowspan: th.attr('rowspan') || 0 //行单元格
  200. }, itemData);
  201. if(row.colspan < 2) cols.push(row);
  202. options.cols[i].push(row);
  203. });
  204. });
  205. //获取表体数据
  206. othis.find('tbody>tr').each(function(i1){
  207. var tr = $(this), row = {};
  208. //如果定义了字段名
  209. tr.children('td').each(function(i2, item2){
  210. var td = $(this)
  211. ,field = td.data('field');
  212. if(field){
  213. return row[field] = td.html();
  214. }
  215. });
  216. //如果未定义字段名
  217. layui.each(cols, function(i3, item3){
  218. var td = tr.children('td').eq(i3);
  219. row[item3.field] = td.html();
  220. });
  221. options.data[i1] = row;
  222. });
  223. table.render(options);
  224. });
  225. return that;
  226. }
  227. /**
  228. * 渲染入口方法(核心入口)
  229. */
  230. ,render:function (options) {
  231. table.pushClassIds(options.id);
  232. var inst = new Class(options);
  233. return thisTable.call(inst);
  234. }
  235. /**
  236. * 对应的表格加载完成后执行
  237. * @param tableId
  238. * @param fn
  239. */
  240. ,ready:function (tableId,fn) {
  241. var is=false;
  242. var myDate=new Date();
  243. function isReady() {
  244. if(tableId){
  245. var that=table.getClass(tableId);
  246. if(that&&that.hasOwnProperty('layBody')){
  247. fn(that);
  248. is=true;
  249. }else{
  250. var myDate2=new Date();
  251. var i=myDate2.getTime()-myDate.getTime();
  252. if(i<=(1000*10)&&!is){//大于10秒退出
  253. setTimeout(isReady,50);
  254. }
  255. }
  256. }
  257. }
  258. if(tableId&&fn){
  259. setTimeout(isReady,50);
  260. }
  261. }
  262. /**
  263. * 获取表格选中记录
  264. * @param tableId
  265. * @return {{data: Array, isAll: boolean}}
  266. */
  267. ,checkStatus:function (tableId) {
  268. var nums = 0
  269. ,invalidNum = 0
  270. ,arr = []
  271. ,data = table.getDataList(tableId) || [];
  272. //计算全选个数
  273. layui.each(data, function(i, item){
  274. if(item.constructor === Array){
  275. invalidNum++; //无效数据,或已删除的
  276. return;
  277. }
  278. if(item[table.config.checkName]){
  279. nums++;
  280. arr.push(table.clearCacheKey(item));
  281. }
  282. });
  283. return {
  284. data: arr //选中的数据
  285. ,isAll: data.length ? (nums === (data.length - invalidNum)) : false //是否全选
  286. };
  287. }
  288. /**
  289. * 设置表格复选状态
  290. * @param tableId
  291. * @param value 此值存在时为设置操作
  292. * @returns {*}
  293. */
  294. ,setCheckStatus:function(tableId, fildName, ids){
  295. var retObj=null;
  296. var that=table.getClass(tableId)
  297. ,invalidNum = 0
  298. ,arr = []
  299. ,data = table.getDataList(tableId) || []
  300. ,childs = that.layBody.find('input[name="layTableCheckbox"]')//复选框
  301. ;
  302. if(fildName&&ids){//设置选中
  303. var idsarr=ids.split(',');
  304. idsarr.forEach(function (o) {
  305. // console.log(o);
  306. var temo=null;
  307. data.forEach(function (e) {
  308. var b1=e[fildName]+"";
  309. var b2=o+"";
  310. if(b1==b2){
  311. temo=e;
  312. return;
  313. };
  314. });
  315. if(temo){
  316. var v=temo[table.config.indexName];
  317. that.layBody.find('input[name="layTableCheckbox"][value="'+v+'"]').prop("checked",true);
  318. that.setCheckData(v, true);
  319. }
  320. });
  321. that.syncCheckAll();
  322. that.renderForm('checkbox');
  323. }
  324. return retObj;
  325. }
  326. /**
  327. * 表格单选状态
  328. * @param tableId
  329. * @param value 此值存在时为设置操作
  330. * @returns {*}
  331. */
  332. ,radioStatus:function (tableId) {
  333. var retObj=null;
  334. var nums = 0
  335. ,invalidNum = 0
  336. ,arr = []
  337. ,data = table.getDataList(tableId) || [];
  338. var v=$("input[name='"+TABLE_RADIO_ID+tableId+"']:checked").val();
  339. v=parseInt(v);
  340. data.forEach(function (e) {
  341. if(e[table.config.indexName]==v){
  342. retObj=e;
  343. return;
  344. };
  345. });
  346. return retObj;
  347. }
  348. /**
  349. * 设置表格单选状态
  350. * @param tableId
  351. * @param value 此值存在时为设置操作
  352. * @returns {*}
  353. */
  354. ,setRadioStatus:function (tableId,fildName,value) {
  355. var retObj=null;
  356. var nums = 0
  357. ,invalidNum = 0
  358. ,arr = []
  359. ,data = table.getDataList(tableId) || [];
  360. if(fildName&&value){//设置选中
  361. data.forEach(function (e) {
  362. var b1=e[fildName]+"";
  363. var b2=value+"";
  364. if(b1==b2){
  365. retObj=e;
  366. return;
  367. };
  368. });
  369. if(retObj){
  370. var v=retObj[table.config.indexName];
  371. $("input:radio[name='"+TABLE_RADIO_ID+tableId+"'][value='"+v+"']").prop("checked",true);
  372. form.render('radio');
  373. }
  374. }
  375. return retObj;
  376. }
  377. /**
  378. * 清除临时Key
  379. * @param data
  380. * @return {*}
  381. */
  382. ,clearCacheKey:function (data) {
  383. data = $.extend({}, data);
  384. delete data[table.config.checkName];
  385. delete data[table.config.indexName];
  386. return data;
  387. }
  388. /**
  389. * 刷新数据
  390. * @param id
  391. * @param options
  392. * @return {*}
  393. */
  394. ,query:function (tableId, options) {
  395. var that= table.getClass(tableId);
  396. that.renderTdCss();
  397. that.pullData(that.page, that.loading());
  398. }
  399. /**
  400. * 此方法为整体重新渲染(重量级刷新方法)
  401. * @param id
  402. * @param options
  403. */
  404. ,reload:function (tableId, options) {
  405. var config = thisTable.config[tableId];
  406. options = options || {};
  407. if(!config) return hint.error('The ID option was not found in the table instance');
  408. if(options.data && options.data.constructor === Array) delete config.data;
  409. return table.render($.extend(true, {}, config, options));
  410. }
  411. /**
  412. * 添加一行或多行数据
  413. * @param tableId 表格id
  414. * @param index 在第几个位置插入(从0开始)
  415. * @param data 数据
  416. * @returns {*}
  417. */
  418. ,addRow:function (tableId, index, data) {
  419. var that=table.getClass(tableId)
  420. ,options=that.config
  421. ,invalidNum = 0
  422. ,arr = []
  423. ,list = table.getDataList(tableId) || [];
  424. //插入到父节点后面
  425. list.splice(index,0,data);//更新缓存
  426. table.restNumbers(list);//重置下标
  427. that.resetData(list);
  428. //如果是树状则处理数据
  429. if(options.isTree) {
  430. //处理父级
  431. var uo=that.treeFindUpData(data);
  432. if(uo) {
  433. that.treeNodeOpen(uo, true);//展开节点
  434. that.renderTreeConvertShowName(uo);
  435. }
  436. }
  437. //生成html
  438. var tds=that.renderTr(data,data[table.config.indexName]);
  439. var trs='<tr data-index="'+ data[table.config.indexName] +'"'+that.renderTrUpids(data)+'>'+ tds.join('') + '</tr>';
  440. if(index==0){//在第一个位置插入
  441. var tbody=that.layBody.find('table tbody');
  442. $(tbody).prepend(trs);
  443. that.layBody.find(".layui-none").remove();
  444. }else{
  445. var o=that.layBody.find('[data-index='+(index-1)+']');//父节点dom树
  446. $(o).after(trs);
  447. }
  448. that.renderPage(that.config.page.count+1);//分页渲染
  449. that.restNumbers();
  450. }
  451. /**
  452. * 删除一行或多行数据
  453. * (如果是树状则删除自己和子节点)
  454. * @param tableId
  455. * @param data(1、数组;2、对象)
  456. */
  457. ,delRow:function (tableId, data) {
  458. //1、页面清除 2、缓存清除
  459. var that=table.getClass(tableId)
  460. ,options=that.config
  461. ,list=table.getDataList(tableId);
  462. var sonList=[];//需要删除的数据
  463. var delIds={};//需要删除的数据map
  464. var delDatas=[];
  465. if(!that||!data)return;
  466. if(table.kit.isArray(data)){//是数组,删除多个
  467. delDatas=data;
  468. }else{
  469. delDatas[0]=data;
  470. }
  471. sonList=options.isTree?table.treeFindSonList(that.config.id,delDatas):delDatas;
  472. //页面元素处理
  473. sonList.forEach(function (temo) {
  474. var index=temo[table.config.indexName];
  475. delIds[index]=index;//设置代删除的id集合
  476. var tr = that.layBody.find('tr[data-index="'+ index +'"]');
  477. tr.remove();
  478. });
  479. //数据处理
  480. that.restNumbers();
  481. var newList=[];//重构一个新的数组
  482. for (var i=0,len=list.length;i<len;i++) {
  483. var isP=true;
  484. var temo1=null;
  485. sonList.forEach(function (temo) {
  486. if (temo[table.config.indexName] === list[i][table.config.indexName]) {
  487. isP = false;
  488. }
  489. });
  490. if(isP){
  491. newList.push(list[i]);
  492. }
  493. }
  494. table.restNumbers(newList);
  495. that.resetData(newList);//更新缓存数据
  496. if(options.page)that.renderPage(that.config.page.count-Object.keys(delIds).length);//分页渲染
  497. }
  498. ,restNumbers:function (list) {
  499. if(!list)return;
  500. var i=0;
  501. list.forEach(function (o) {
  502. o[table.config.indexName]=i;
  503. i++;
  504. });
  505. }
  506. /**
  507. * 获取全部需要子节点对象集合
  508. * @param data(数组或对象)
  509. */
  510. ,treeFindSonList:function (tableId,data) {
  511. var that=table.getClass(tableId);
  512. if(!that||!data)return [];
  513. var delDatas=[];
  514. var sonList=[];//需要删除的数据
  515. var delIds={};//需要删除的数据map
  516. if(table.kit.isArray(data)){//是数组,删除多个
  517. delDatas=data;
  518. }else{
  519. delDatas[0]=data;
  520. }
  521. delDatas.forEach(function (temo) {
  522. if(temo.children.length>0){
  523. var temSonList=that.treeFindSonData(temo);
  524. temSonList.forEach(function (temii) {
  525. if(!delIds[temii[table.config.indexName]]){
  526. sonList.push(temii);
  527. delIds[temii[table.config.indexName]]=temii[table.config.indexName];
  528. }
  529. });
  530. }
  531. sonList.push(temo);
  532. delIds[temo[table.config.indexName]]=temo[table.config.indexName];
  533. });
  534. return sonList;
  535. }
  536. /**
  537. * 获取全部需要子节点id集合
  538. * @param data(数组或对象)
  539. */
  540. ,treeFindSonIds:function (tableId,data) {
  541. var delIds=[];
  542. var sonList=table.treeFindSonList(tableId,data);
  543. sonList.forEach(function (temo) {
  544. delIds.push([table.config.indexName]);
  545. });
  546. return delIds;
  547. }
  548. /**
  549. * 获取全部的id字段集合
  550. * @param tableId
  551. * @param data
  552. * @returns {Array}
  553. */
  554. ,treeFindSonIdFields:function (tableId,data) {
  555. var idField=[];
  556. var that=table.getClass(tableId);
  557. var sonList=table.treeFindSonList(tableId,data);
  558. sonList.forEach(function (temo) {
  559. idField.push(temo[that.config.idField]);
  560. });
  561. return idField;
  562. }
  563. /**
  564. * 工具方法对象
  565. */
  566. ,kit:{
  567. isArray:function (o) {
  568. return Object.prototype.toString.call(o) === '[object Array]';
  569. }
  570. }
  571. }
  572. //操作当前实例
  573. ,thisTable = function(){
  574. var that = this
  575. ,options = that.config
  576. ,id = options.id;
  577. id && (thisTable.config[id] = options);
  578. return {
  579. reload: function(options){
  580. that.reload.call(that, options);
  581. }
  582. ,config: options
  583. }
  584. }
  585. //字符常量
  586. ,MOD_NAME = 'dltable', ELEM = '.layui-table', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled', NONE = 'layui-none'
  587. ,ELEM_VIEW = 'layui-table-view', ELEM_HEADER = '.layui-table-header', ELEM_BODY = '.layui-table-body', ELEM_MAIN = '.layui-table-main', ELEM_FIXED = '.layui-table-fixed', ELEM_FIXL = '.layui-table-fixed-l', ELEM_FIXR = '.layui-table-fixed-r', ELEM_TOOL = '.layui-table-tool', ELEM_PAGE = '.layui-table-page', ELEM_SORT = '.layui-table-sort', ELEM_EDIT = 'layui-table-edit', ELEM_HOVER = 'layui-table-hover'
  588. ,TABLE_RADIO_ID='table_radio_'
  589. ,ELEM_FILTER='.layui-table-filter'
  590. ,TREE_ID='treeId',TREE_UPID='treeUpId',TREE_SHOW_NAME='treeShowName',TREE_KEY_MAP='tree_key_map'
  591. //thead区域模板
  592. ,TPL_HEADER = function(options){
  593. var rowCols = '{{#if(item2.colspan){}} colspan="{{item2.colspan}}"{{#} if(item2.rowspan){}} rowspan="{{item2.rowspan}}"{{#}}}';
  594. options = options || {};
  595. return ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
  596. ,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
  597. ,'<thead>'
  598. ,'{{# layui.each(d.data.cols, function(i1, item1){ }}'
  599. ,'<tr>'
  600. ,'{{# layui.each(item1, function(i2, item2){ }}'
  601. ,'{{# if(item2.fixed && item2.fixed !== "right"){ left = true; } }}'
  602. ,'{{# if(item2.fixed === "right"){ right = true; } }}'
  603. ,function(){
  604. if(options.fixed && options.fixed !== 'right'){
  605. return '{{# if(item2.fixed && item2.fixed !== "right"){ }}';
  606. }
  607. if(options.fixed === 'right'){
  608. return '{{# if(item2.fixed === "right"){ }}';
  609. }
  610. return '';
  611. }()
  612. ,'<th data-field="{{ item2.field||i2 }}" {{# if(item2.minWidth){ }}data-minwidth="{{item2.minWidth}}"{{# } }} '+ rowCols +' {{# if(item2.unresize){ }}data-unresize="true"{{# } }}>'
  613. ,'<div class="layui-table-cell laytable-cell-'
  614. ,'{{# if(item2.colspan > 1){ }}'
  615. ,'group'
  616. ,'{{# } else { }}'
  617. ,'{{d.index}}-{{item2.field || i2}}'
  618. ,'{{# if(item2.type !== "normal"){ }}'
  619. ,' laytable-cell-{{ item2.type }}'
  620. ,'{{# } }}'
  621. ,'{{# } }}'
  622. ,'" {{#if(item2.align){}}align="{{item2.align}}"{{#}}}>'
  623. ,'{{# if(item2.type === "checkbox"){ }}' //复选框
  624. ,'<input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose" {{# if(item2[d.data.checkName]){ }}checked{{# }; }}>'
  625. ,'{{# } else { }}'
  626. ,'<span>{{item2.title||""}}</span>'
  627. ,'{{# if(!(item2.colspan > 1) && item2.sort){ }}'
  628. ,'<span class="layui-table-sort layui-inline"><i class="layui-edge layui-table-sort-asc"></i><i class="layui-edge layui-table-sort-desc"></i></span>'
  629. ,'{{# } }}'
  630. ,'{{# } }}'
  631. ,'</div>'
  632. ,'</th>'
  633. ,(options.fixed ? '{{# }; }}' : '')
  634. ,'{{# }); }}'
  635. ,'</tr>'
  636. ,'{{# }); }}'
  637. ,'</thead>'
  638. ,'</table>'].join('');
  639. }
  640. /**
  641. * 行内过滤区域
  642. */
  643. ,TPL_FILTER = function(options){
  644. }
  645. //tbody区域模板
  646. ,TPL_BODY = ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
  647. ,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
  648. ,'<tbody></tbody>'
  649. ,'</table>'].join('')
  650. //主模板
  651. ,TPL_MAIN = ['<div class="layui-form layui-border-box {{d.VIEW_CLASS}}" lay-filter="LAY-table-{{d.index}}" style="{{# if(d.data.width){ }}width:{{d.data.width}}px;{{# } }} {{# if(d.data.height){ }}height:{{d.data.height}}px;{{# } }}">'
  652. ,'{{# if(d.data.toolbar){ }}'
  653. ,'<div class="layui-table-tool"></div>'
  654. ,'{{# } }}'
  655. ,'<div class="layui-table-box">'
  656. ,'{{# var left, right; }}'
  657. ,'<div class="layui-table-header">'
  658. ,TPL_HEADER()
  659. ,'</div>'
  660. ,'<div class="layui-table-filter">'
  661. ,TPL_FILTER()
  662. ,'</div>'
  663. ,'<div class="layui-table-body layui-table-main">'
  664. ,TPL_BODY
  665. ,'</div>'
  666. ,'{{# if(left){ }}'
  667. ,'<div class="layui-table-fixed layui-table-fixed-l">'
  668. ,'<div class="layui-table-header">'
  669. ,TPL_HEADER({fixed: true})
  670. ,'</div>'
  671. ,'<div class="layui-table-body">'
  672. ,TPL_BODY
  673. ,'</div>'
  674. ,'</div>'
  675. ,'{{# }; }}'
  676. ,'{{# if(right){ }}'
  677. ,'<div class="layui-table-fixed layui-table-fixed-r">'
  678. ,'<div class="layui-table-header">'
  679. ,TPL_HEADER({fixed: 'right'})
  680. ,'<div class="layui-table-mend"></div>'
  681. ,'</div>'
  682. ,'<div class="layui-table-body">'
  683. ,TPL_BODY
  684. ,'</div>'
  685. ,'</div>'
  686. ,'{{# }; }}'
  687. ,'</div>'
  688. ,'{{# if(d.data.page){ }}'
  689. ,'<div class="layui-table-page">'
  690. ,'<div id="layui-table-page{{d.index}}"></div>'
  691. ,'</div>'
  692. ,'{{# } }}'
  693. /*,'<style>'
  694. ,'{{# layui.each(d.data.cols, function(i1, item1){'
  695. ,'layui.each(item1, function(i2, item2){ }}'
  696. ,'.laytable-cell-{{d.index}}-{{item2.field||i2}}{ '
  697. ,'{{# if(item2.width){ }}'
  698. ,'width: {{item2.width}}px;'
  699. ,'{{# } }}'
  700. ,' }'
  701. ,'{{# });'
  702. ,'}); }}'
  703. ,'</style>'*/
  704. ,'</div>'].join('')
  705. ,_WIN = $(window)
  706. ,_DOC = $(document)
  707. //构造器
  708. ,Class = function(options){
  709. var that = this;
  710. that.index = ++table.index;
  711. that.config = $.extend({}, that.config, table.config, options);
  712. that.render();
  713. table.pushClass(options.id,that);
  714. };
  715. //默认配置
  716. Class.prototype.config = {
  717. limit: 10 //每页显示的数量
  718. ,loading: true //请求数据时,是否显示loading
  719. ,cellMinWidth: 60 //所有单元格默认最小宽度
  720. ,text: {
  721. none: '无数据'
  722. }
  723. ,isFilter:false//是否开启行内过滤
  724. ,method:'post'//默认以post方式请求后台
  725. };
  726. //表格渲染
  727. Class.prototype.render = function(){
  728. var that = this
  729. ,options = that.config;
  730. options.elem = $(options.elem);
  731. options.where = options.where || {};
  732. options.id = options.id || options.elem.attr('id');
  733. //请求参数的自定义格式
  734. options.request = $.extend({
  735. pageName: 'page'
  736. ,limitName: 'limit'
  737. }, options.request)
  738. //响应数据的自定义格式
  739. options.response = $.extend({
  740. statusName: 'code'
  741. ,statusCode: 0
  742. ,msgName: 'msg'
  743. ,dataName: 'data'
  744. ,countName: 'count'
  745. }, options.response);
  746. //如果 page 传入 laypage 对象
  747. if(typeof options.page === 'object'){
  748. options.limit = options.page.limit || options.limit;
  749. options.limits = options.page.limits || options.limits;
  750. that.page = options.page.curr = options.page.curr || 1;
  751. delete options.page.elem;
  752. delete options.page.jump;
  753. }
  754. if(!options.elem[0]) return that;
  755. that.setArea(); //动态分配列宽高
  756. //开始插入替代元素
  757. var othis = options.elem
  758. ,hasRender = othis.next('.' + ELEM_VIEW)
  759. //主容器
  760. ,reElem = that.elem = $(laytpl(TPL_MAIN).render({
  761. VIEW_CLASS: ELEM_VIEW
  762. ,data: options
  763. ,index: that.index //索引
  764. }));
  765. options.index = that.index;
  766. //生成替代元素
  767. hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender
  768. othis.after(reElem);
  769. that.renderTdCss();
  770. //各级容器
  771. that.layHeader = reElem.find(ELEM_HEADER); //表头
  772. that.layMain = reElem.find(ELEM_MAIN);//内容区域
  773. that.layBody = reElem.find(ELEM_BODY);//内容区域
  774. that.layFixed = reElem.find(ELEM_FIXED);//浮动区域
  775. that.layFixLeft = reElem.find(ELEM_FIXL);//左浮动
  776. that.layFixRight = reElem.find(ELEM_FIXR);//有浮动
  777. that.layTool = reElem.find(ELEM_TOOL);//工具栏区域
  778. that.layPage = reElem.find(ELEM_PAGE);//分页区域
  779. that.layFilter=reElem.find(ELEM_FILTER);//行内过滤条件区域
  780. that.layTool.html(
  781. laytpl($(options.toolbar).html()||'').render(options)
  782. );
  783. if(options.height) that.fullSize(); //设置body区域高度
  784. //如果多级表头,则填补表头高度
  785. if(options.cols.length > 1){
  786. var th = that.layFixed.find(ELEM_HEADER).find('th');
  787. th.height(that.layHeader.height() - 1 - parseFloat(th.css('padding-top')) - parseFloat(th.css('padding-bottom')));
  788. }
  789. //渲染过滤区域
  790. if(options.isFilter){
  791. that.layFilter.html(
  792. that.renderFilter()
  793. );
  794. }
  795. //请求数据
  796. that.pullData(that.page);
  797. that.events();
  798. };
  799. //根据列类型,定制化参数
  800. Class.prototype.initOpts = function(item){
  801. var that = this,
  802. options = that.config
  803. ,initWidth = {
  804. checkbox: 48
  805. ,space: 15
  806. ,numbers: 40
  807. };
  808. //让 type 参数兼容旧版本
  809. if(item.checkbox) item.type = "checkbox";
  810. if(item.space) item.type = "space";
  811. if(!item.type) item.type = "normal";
  812. if(item.type !== "normal"){
  813. item.unresize = true;
  814. item.width = item.width || initWidth[item.type];
  815. }
  816. if(options.isFilter){//开启行内过滤
  817. if(item.isFilter!=false){
  818. item.isFilter=true;
  819. }
  820. }
  821. };
  822. //动态分配列宽高
  823. Class.prototype.setArea = function(){
  824. var that = this,
  825. options = that.config
  826. ,colNums = 0 //列个数
  827. ,autoColNums = 0 //自动列宽的列个数
  828. ,autoWidth = 0 //自动列分配的宽度
  829. ,countWidth = 0 //所有列总宽度和
  830. ,cntrWidth = options.width ||function(){ //获取容器宽度
  831. //如果父元素宽度为0(一般为隐藏元素),则继续查找上层元素,直到找到真实宽度为止
  832. var getWidth = function(parent){
  833. var width, isNone;
  834. parent = parent || options.elem.parent()
  835. width = parent.width();
  836. try {
  837. isNone = parent.css('display') === 'none';
  838. } catch(e){}
  839. if(parent[0] && (!width || isNone)) return getWidth(parent.parent());
  840. return width;
  841. };
  842. return getWidth();
  843. }();
  844. //统计列个数
  845. that.eachCols(function(){
  846. colNums++;
  847. });
  848. //减去边框差
  849. cntrWidth = cntrWidth - function(){
  850. return (options.skin === 'line' || options.skin === 'nob') ? 2 : colNums + 1;
  851. }();
  852. //遍历所有列
  853. layui.each(options.cols, function(i1, item1){
  854. layui.each(item1, function(i2, item2){
  855. var width;
  856. if(!item2){
  857. item1.splice(i2, 1);
  858. return;
  859. }
  860. that.initOpts(item2);
  861. width = item2.width || 0;
  862. if(item2.colspan > 1) return;
  863. if(/\d+%$/.test(width)){
  864. item2.width = width = Math.floor((parseFloat(width) / 100) * cntrWidth);
  865. } else if(item2._is_width_dev||!width){ //列宽未填写
  866. item2._is_width_dev=true;//采用默认宽度的列
  867. item2.width = width = 0;
  868. autoColNums++;
  869. }
  870. countWidth = countWidth + width;
  871. });
  872. });
  873. that.autoColNums = autoColNums; //记录自动列数
  874. //如果未填充满,则将剩余宽度平分。否则,给未设定宽度的列赋值一个默认宽
  875. (cntrWidth > countWidth && autoColNums) && (
  876. autoWidth = (cntrWidth - countWidth) / autoColNums
  877. );
  878. layui.each(options.cols, function(i1, item1){
  879. layui.each(item1, function(i2, item2){
  880. var minWidth = item2.minWidth || options.cellMinWidth;
  881. if(item2.colspan > 1) return;
  882. if(item2.width === 0){
  883. item2.width = Math.floor(autoWidth >= minWidth ? autoWidth : minWidth); //不能低于设定的最小宽度
  884. }
  885. });
  886. });
  887. //高度铺满:full-差距值
  888. var th=that.getParentDivHeight(options.id);
  889. that.fullHeightGap=0;
  890. if(options.height){
  891. if(/^full-\d+$/.test(options.height)){
  892. that.fullHeightGap = options.height.split('-')[1];
  893. }
  894. }
  895. options.height = th - that.fullHeightGap;
  896. layui.each(options.cols, function(i1, item1){
  897. layui.each(item1, function(i2, item2){
  898. })
  899. });
  900. };
  901. /**
  902. * 表格获取父容器高度
  903. * @param tableId
  904. */
  905. Class.prototype.getParentDivHeight = function(tableId){
  906. var th=$("#"+tableId).parent().height();
  907. return th;
  908. };
  909. //表格重载
  910. Class.prototype.reload = function(options){
  911. var that = this;
  912. if(that.config.data && that.config.data.constructor === Array) delete that.config.data;
  913. that.config = $.extend({}, that.config, options);
  914. //获取行内过滤的值
  915. that.render();
  916. };
  917. //页码
  918. Class.prototype.page = 1;
  919. /**
  920. * 重置下标(插入删除等操作)
  921. * 1、data-index中的下标
  922. * 2、tr中data的值
  923. * 3、下标字段的值
  924. * @param list
  925. */
  926. Class.prototype.restNumbers=function(){
  927. var that = this
  928. ,options = that.config;
  929. var trs=that.layBody.find('table tbody tr');
  930. var i=0;
  931. trs.each(function (o) {
  932. $(this).attr("data-index",i);
  933. $(this).find(".laytable-cell-numbers p").text(i+1);
  934. $(this).data('index',i);
  935. i++;
  936. });
  937. }
  938. /**
  939. * 重置当前表格的数据(1、普通列表;2树状表格)
  940. * 将列表数据转成树形结构和符合table展示的列表
  941. * @param list 列表数据
  942. * @param field_Id 树形结构主键字段
  943. * @param field_upId 树形结构上级字段
  944. * @returns {Array} [0]表格列表 [1]树形结构
  945. */
  946. Class.prototype.resetData=function(list) {
  947. var that = this
  948. ,options = that.config;
  949. var datas=[];
  950. var treeList=[];
  951. var tableList=[];
  952. var map={};//列表map,fieldId为key
  953. datas.push(tableList);//table结构
  954. datas.push(treeList)//tree树结构
  955. datas.push(map)//data数据 map结构
  956. if(list==null||list.length<=0)return datas;
  957. //设置默认参数
  958. for (var i = 0; i < list.length; i++) {
  959. var n = list[i];
  960. if(options.isTree){
  961. if(!n.hasOwnProperty("is_open")){//如果不存在该属性则默认为true
  962. n.is_open=true;
  963. }
  964. if(!n.hasOwnProperty("is_show")){//如果不存在该属性则默认为true
  965. n.is_show=true;
  966. }
  967. }
  968. }
  969. if(options.isTree){//树状
  970. var field_Id=options[TREE_ID];
  971. var field_upId=options[TREE_UPID];
  972. //处理树结构
  973. var fa = function(upId) {
  974. var _array = [];
  975. for (var i = 0; i < list.length; i++) {
  976. var n = list[i];
  977. if (n[field_upId] === upId) {
  978. n.children = fa(n[field_Id]);
  979. _array.push(n);
  980. }
  981. }
  982. return _array;
  983. }
  984. treeList=fa(list[0][field_upId],"");//递归
  985. //处理表格结构
  986. var fa2=function (l,level,upids) {
  987. for (var i = 0; i < l.length; i++) {
  988. var n = l[i];
  989. n.level=level;//设置当前层级
  990. n.upIds=upids;
  991. tableList.push(n);
  992. if (n.children&&n.children.length>0) {
  993. fa2(n.children,1+level,upids+"_"+n[field_Id]+"_");
  994. }
  995. }
  996. return;
  997. }
  998. fa2(treeList,1,"");
  999. }
  1000. else{
  1001. tableList=list;
  1002. }
  1003. //设置map数据集合
  1004. tableList.forEach(function (o) {
  1005. map[o[field_Id]]=o;
  1006. });
  1007. //设置到内存中去
  1008. table.setDataList(that.config.id,tableList);
  1009. table.setDataTreeList(that.config.id,treeList);
  1010. table.setDataMap(that.config.id,map);
  1011. return datas;
  1012. }
  1013. /**
  1014. * 根据id从表格数据中获取对象
  1015. * @param data
  1016. * @param field_Id
  1017. * @param field_upId
  1018. * @returns {Array}
  1019. */
  1020. Class.prototype.treeFindDataById=function(u_Id) {
  1021. var that = this
  1022. ,options = that.config;
  1023. var e=null;
  1024. var list=table.getDataList(that.key);
  1025. var key=options[TREE_ID];
  1026. list.forEach(function (o) {
  1027. if(o[key]==u_Id){
  1028. e=o;
  1029. return;
  1030. }
  1031. });
  1032. return e;
  1033. }
  1034. /**
  1035. * 获取父节点
  1036. * @param u_Id
  1037. */
  1038. Class.prototype.treeFindUpData=function(o){
  1039. var uOjb=null;
  1040. var that = this
  1041. ,options = that.config;
  1042. //处理父级
  1043. var key=options[TREE_UPID];//父节点key名称
  1044. var mapData=table.getDataMap(that.config.id);//获取map形式对象集合
  1045. uOjb=mapData[o[key]];
  1046. return uOjb;
  1047. }
  1048. /**
  1049. * 根据父id获取全部的叶子节点(递归)
  1050. * @param o 数据对象
  1051. * @return {string}
  1052. */
  1053. Class.prototype.treeFindSonData=function (data) {
  1054. var objs=[];
  1055. function f(o) {
  1056. if(o.children.length>0){
  1057. o.children.forEach(function (i) {
  1058. objs.push(i);
  1059. if(i.children.length>0){
  1060. f(i);
  1061. }
  1062. });
  1063. }
  1064. }f(data);
  1065. return objs;
  1066. };
  1067. /**
  1068. * 叶子节点显示转换
  1069. * @param o 数据
  1070. * @param fieldName 树显示列名
  1071. * @returns {string}
  1072. */
  1073. Class.prototype.treeConvertShowName=function (o) {
  1074. var that = this
  1075. ,options = that.config;
  1076. var isTreeNode=(o.children&&o.children.length>0);
  1077. var temhtml='<div style="float: left;height: 28px;line-height: 28px;padding-left: '+
  1078. function () {
  1079. if(isTreeNode){
  1080. return '5px'
  1081. }else{
  1082. return '21px'
  1083. }
  1084. }()
  1085. +'">'
  1086. +function () {//位移量
  1087. var nbspHtml="<i>"//一次位移
  1088. for(var i=1;i<o.level;i++) {
  1089. nbspHtml = nbspHtml + "&nbsp;&nbsp;&nbsp;&nbsp;";
  1090. }
  1091. nbspHtml=nbspHtml+"</i>";
  1092. return nbspHtml;
  1093. }()
  1094. +function () {//图标或占位符
  1095. var temTreeHtml='';
  1096. if(isTreeNode)temTreeHtml='<i class="layui-icon layui-tree-head">&#xe625;</i> ';
  1097. return temTreeHtml;
  1098. }()
  1099. +'</div>';
  1100. return temhtml;
  1101. };
  1102. /**
  1103. * 节点的展开或折叠
  1104. * @param o 节点数据(树状表格)
  1105. * @param is_open 展开(true)或折叠(false)
  1106. *
  1107. * 每个节点有两种状态,
  1108. * 1、打开状态(is_open) 打开状态只需在点击瞬间控制,其他时候不需要变动
  1109. * 2、显示状态(显示或隐藏) 显示状态根据父级节点控制,父级节点是显示并且打开状态的则显示,否则不显示,但不影响其打开状态
  1110. */
  1111. Class.prototype.treeNodeOpen=function (o,is_open) {
  1112. var that = this
  1113. ,options = that.config
  1114. ,tr = that.layBody.find('tr[data-index="'+ o[table.config.indexName] +'"]');
  1115. o.is_open=is_open;
  1116. //处理树结构
  1117. var fa = function(e) {
  1118. if(e.children&&e.children.length>0){
  1119. var temList=e.children;
  1120. for (var i = 0; i < temList.length; i++) {
  1121. var n = temList[i];
  1122. if(o.is_open){//打开状态的,关闭
  1123. if(e.is_open&&e.is_show){//该节点显示
  1124. var temo=that.layBody.find('tr[data-index="'+ n[table.config.indexName] +'"]');
  1125. temo.show();
  1126. n.is_show=true;
  1127. }
  1128. }else{
  1129. var temo=that.layBody.find('tr[data-index="'+ n[table.config.indexName] +'"]');
  1130. temo.hide();
  1131. n.is_show=false;
  1132. }
  1133. fa(n);
  1134. }
  1135. }
  1136. }
  1137. fa(o);
  1138. //处理图标
  1139. var dbClickI=tr.find('.layui-tree-head');
  1140. if(o.is_open){//打开状态
  1141. dbClickI.html('&#xe625;');
  1142. }else{
  1143. dbClickI.html('&#xe623;');
  1144. }
  1145. };
  1146. //获得数据
  1147. Class.prototype.pullData = function(curr, loadIndex){
  1148. var that = this
  1149. ,options = that.config
  1150. ,request = options.request
  1151. ,response = options.response
  1152. ,sort = function(){
  1153. if(typeof options.initSort === 'object'){
  1154. that.sort(options.initSort.field, options.initSort.type);
  1155. }
  1156. };
  1157. that.startTime = new Date().getTime(); //渲染开始时间
  1158. if(options.url){ //Ajax请求
  1159. var params = {};
  1160. params[request.pageName] = curr;
  1161. params[request.limitName] = options.limit;
  1162. //行内过滤条件
  1163. var list=that.layFilter.find("[name^='filter_']");
  1164. layui.each(list,function (i, o) {
  1165. params[o.name]=$(o).val();
  1166. });
  1167. $.ajax({
  1168. type: options.method || 'get'
  1169. ,url: options.url
  1170. ,data: $.extend(params, options.where)
  1171. ,dataType: 'json'
  1172. ,success: function(res){
  1173. if(res.data.length){
  1174. let arr = [],obj = res.data;
  1175. (function objArr(obj,id) {
  1176. for (let i in obj) {
  1177. obj[i].myid = id+i;
  1178. obj[i].myPid = id;
  1179. if (obj[i].childMenus != null) {
  1180. objArr(obj[i].childMenus,id+i);
  1181. obj[i].childMenus = null;
  1182. arr.push(obj[i]);
  1183. } else {
  1184. arr.push(obj[i]);
  1185. }
  1186. }
  1187. })(obj,'#');
  1188. res.data = arr.reverse();
  1189. console.log(res.data);
  1190. res.is = true;
  1191. res.count = res.data.length;
  1192. }else{
  1193. res.data[0] = {name:"无数据",myid:'0',myPid:'0',id:'0'};
  1194. }
  1195. that.resetData(res.data);
  1196. res.data=table.getDataList(options.id);
  1197. if(res[response.statusName] != response.statusCode){
  1198. that.renderForm();
  1199. that.layMain.html('<div class="'+ NONE +'">'+ (res[response.msgName] || '返回的数据状态异常') +'</div>');
  1200. } else {
  1201. that.renderData(res, curr, res[response.countName]), sort();
  1202. options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时(接口请求+视图渲染)
  1203. }
  1204. loadIndex && layer.close(loadIndex);
  1205. typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
  1206. }
  1207. ,error: function(e, m){
  1208. that.layMain.html('<div class="'+ NONE +'">数据接口请求异常</div>');
  1209. that.renderForm();
  1210. loadIndex && layer.close(loadIndex);
  1211. }
  1212. });
  1213. } else if(options.data && options.data.constructor === Array){ //已知数据
  1214. var res = {},startLimit = curr*options.limit - options.limit
  1215. res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
  1216. res[response.countName] = options.data.length;
  1217. that.renderData(res, curr, options.data.length), sort();
  1218. typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
  1219. }
  1220. };
  1221. //遍历表头
  1222. Class.prototype.eachCols = function(callback){
  1223. var cols = $.extend(true, [], this.config.cols)
  1224. ,arrs = [], index = 0;
  1225. //重新整理表头结构
  1226. layui.each(cols, function(i1, item1){
  1227. layui.each(item1, function(i2, item2){
  1228. //如果是组合列,则捕获对应的子列
  1229. if(item2.colspan > 1){
  1230. var childIndex = 0;
  1231. index++
  1232. item2.CHILD_COLS = [];
  1233. layui.each(cols[i1 + 1], function(i22, item22){
  1234. if(item22.PARENT_COL || childIndex == item2.colspan) return;
  1235. item22.PARENT_COL = index;
  1236. item2.CHILD_COLS.push(item22);
  1237. childIndex = childIndex + (item22.colspan > 1 ? item22.colspan : 1);
  1238. });
  1239. }
  1240. if(item2.PARENT_COL) return; //如果是子列,则不进行追加,因为已经存储在父列中
  1241. arrs.push(item2)
  1242. });
  1243. });
  1244. //重新遍历列,如果有子列,则进入递归
  1245. var eachArrs = function(obj){
  1246. layui.each(obj || arrs, function(i, item){
  1247. if(item.CHILD_COLS) return eachArrs(item.CHILD_COLS);
  1248. callback(i, item);
  1249. });
  1250. };
  1251. eachArrs();
  1252. };
  1253. /**
  1254. * 渲染节点显示
  1255. * @param callback
  1256. */
  1257. Class.prototype.renderTreeConvertShowName = function(o){
  1258. var that = this
  1259. ,options = that.config
  1260. ,m=options.elem
  1261. ,hasRender = m.next('.' + ELEM_VIEW);
  1262. var temhtml=that.treeConvertShowName(o);
  1263. var temdiv=that.layBody.find('tr[data-index="'+ o[table.config.indexName] +'"]').find('td[data-field='+options[TREE_SHOW_NAME]+']').find('.layui-table-cell');
  1264. $(temdiv).find('div').remove();
  1265. $(temdiv).prepend(temhtml);
  1266. }
  1267. /**
  1268. * 渲染表格单元格样式(宽度样式设置)
  1269. * @param callback
  1270. */
  1271. Class.prototype.renderTdCss = function(){
  1272. var that = this
  1273. ,options = that.config
  1274. ,m=options.elem
  1275. ,hasRender = m.next('.' + ELEM_VIEW);
  1276. var id=that.index+'_dltable_td_style';
  1277. hasRender.find("#"+id).remove();
  1278. var styel='<style id="'+id+'">'
  1279. +function () {
  1280. var ret="";
  1281. layui.each(that.config.cols,function (i1, item1) {
  1282. layui.each(item1, function(i2, item2){
  1283. ret+='.laytable-cell-'+that.index+'-'+(item2.field||i2)+'{' +
  1284. 'width:'+(item2.width?item2.width+"px":"0px")
  1285. +'}';
  1286. });
  1287. });
  1288. return ret;
  1289. }()+'</style>';
  1290. hasRender.append(styel);
  1291. }
  1292. /**
  1293. * 生成单元格
  1294. * @param obj 行数据
  1295. * @param numbers 下标
  1296. * @param cols 列定义数据
  1297. * @param i3 第几列
  1298. */
  1299. Class.prototype.renderTrUpids=function (obj) {
  1300. var that = this
  1301. ,options = that.config;
  1302. var tree_upid_key=options[TREE_UPID];
  1303. var upids=' upids="'+obj["upIds"]+'" ';
  1304. var u_id=' u_id="'+obj[tree_upid_key]+'" '
  1305. var ret=options.isTree?u_id:'';
  1306. return ret;
  1307. }
  1308. /**
  1309. * 生成单元格
  1310. * @param obj 行数据
  1311. * @param numbers 下标
  1312. * @param cols 列定义数据
  1313. * @param i3 第几列
  1314. */
  1315. Class.prototype.renderTd=function (param) {
  1316. var that = this
  1317. ,options = that.config;
  1318. var cols=param.cols;
  1319. var obj=param.obj;
  1320. var numbers=param.numbers;
  1321. var i3=param.i3;
  1322. var field = cols.field || i3, content = obj[field]||''
  1323. ,cell = that.getColElem(that.layHeader, field);
  1324. var treeImgHtml='';
  1325. if(options.isTree){
  1326. if(options.treeShowName==cols.field){
  1327. treeImgHtml=that.treeConvertShowName(obj);
  1328. }
  1329. }
  1330. //td内容
  1331. var td = ['<td data-field="'+ field +'" '+ function(){
  1332. var attr = [];
  1333. if(cols.edit) attr.push('data-edit="'+ cols.edit +'"'); //是否允许单元格编辑
  1334. if(cols.align) attr.push('align="'+ cols.align +'"'); //对齐方式
  1335. if(cols.templet) attr.push('data-content="'+ content +'"'); //自定义模板
  1336. if(cols.toolbar) attr.push('data-off="true"'); //自定义模板
  1337. if(cols.event) attr.push('lay-event="'+ cols.event +'"'); //自定义事件
  1338. if(cols.style) attr.push('style="'+ cols.style +'"'); //自定义样式
  1339. if(cols.minWidth) attr.push('data-minwidth="'+ cols.minWidth +'"'); //单元格最小宽度
  1340. return attr.join(' ');
  1341. }() +'>'
  1342. ,'<div class="layui-table-cell laytable-cell-'+ function(){ //返回对应的CSS类标识
  1343. var str = (options.index + '-' + field);
  1344. return cols.type === 'normal' ? str
  1345. : (str + ' laytable-cell-' + cols.type);
  1346. }() +'">'+treeImgHtml+'<p style="width: auto;height: 100%;">'+ function(){
  1347. var tplData = $.extend(true, {
  1348. LAY_INDEX: numbers
  1349. }, obj);
  1350. //渲染复选框列视图
  1351. if(cols.type === 'checkbox'){
  1352. return '<input type="checkbox" name="layTableCheckbox" value="'+tplData[table.config.indexName]+'" lay-skin="primary" '+ function(){
  1353. var checkName = table.config.checkName;
  1354. //如果是全选
  1355. if(cols[checkName]){
  1356. obj[checkName] = cols[checkName];
  1357. return cols[checkName] ? 'checked' : '';
  1358. }
  1359. return tplData[checkName] ? 'checked' : '';
  1360. }() +'>';
  1361. } else if(cols.type === 'numbers'){ //渲染序号
  1362. return numbers;
  1363. }else if(cols.type === 'drop'){//下拉框
  1364. var rowsField=dl.ui.table.drop.findFieldObj(options.cols[0],field);
  1365. if(rowsField&&rowsField['drop']){
  1366. var o=dl.cache.code.get(rowsField.drop);
  1367. return dl.ui.table.drop.findDropLable(rowsField.drop,content);
  1368. }
  1369. }else if(cols.type === 'radio'){//单选
  1370. return '<input type="radio" name="'+TABLE_RADIO_ID+options.id+'" value="'+tplData[table.config.indexName]+'" checked="">';
  1371. }
  1372. //解析工具列模板
  1373. if(cols.toolbar){
  1374. return laytpl($(cols.toolbar).html()||'').render(tplData);
  1375. }
  1376. return cols.templet ? function(){
  1377. return typeof cols.templet === 'function'
  1378. ? cols.templet(tplData)
  1379. : laytpl($(cols.templet).html() || String(content)).render(tplData)
  1380. }() : content;
  1381. }()
  1382. ,'</p></div></td>'].join('');
  1383. return td;
  1384. }
  1385. /**
  1386. * 生成tr中的一行
  1387. * @param obj 行数据
  1388. * @param numbers 行号
  1389. * @returns {*}
  1390. */
  1391. Class.prototype.renderTr=function (obj,numbers) {
  1392. var that = this
  1393. ,options = that.config;
  1394. var tds= [];
  1395. that.eachCols(function(i3, cols){//cols列定义
  1396. var field = cols.field || i3, content = obj[field]
  1397. ,cell = that.getColElem(that.layHeader, field);
  1398. if(content === undefined || content === null) content = '';
  1399. if(cols.colspan > 1) return;
  1400. //td内容
  1401. var td = that.renderTd({
  1402. 'obj':obj,'numbers':numbers,'cols':cols,'i3':i3
  1403. });
  1404. tds.push(td);
  1405. // if(item3.fixed && item3.fixed !== 'right') tds_fixed.push(td);
  1406. // if(item3.fixed === 'right') tds_fixed_r.push(td);
  1407. });
  1408. return tds;
  1409. };
  1410. /**
  1411. * 表格数据部分渲染入口
  1412. * @param res
  1413. * @param curr
  1414. * @param count
  1415. * @param sort
  1416. */
  1417. Class.prototype.renderData = function(res, curr, count, sort){
  1418. var that = this
  1419. ,options = that.config
  1420. ,data = res[options.response.dataName] || []
  1421. ,trs = []
  1422. ,trs_fixed = []
  1423. ,trs_fixed_r = []
  1424. //渲染视图
  1425. ,render = function(){ //后续性能提升的重点
  1426. if(!sort && that.sortKey){
  1427. return that.sort(that.sortKey.field, that.sortKey.sort, true);
  1428. }
  1429. layui.each(data, function(i1, obj){
  1430. var tds = [], tds_fixed = [], tds_fixed_r = []
  1431. ,numbers = i1 + options.limit*(curr - 1) + 1; //序号
  1432. if(obj.length === 0) return;
  1433. if(!sort){
  1434. obj[table.config.indexName] = i1;
  1435. }
  1436. tds=that.renderTr(obj,numbers);
  1437. trs.push('<tr data-index="'+ i1 +'" '+that.renderTrUpids(obj)+'>'+ tds.join('') + '</tr>');
  1438. trs_fixed.push('<tr data-index="'+ i1 +'">'+ tds_fixed.join('') + '</tr>');
  1439. trs_fixed_r.push('<tr data-index="'+ i1 +'">'+ tds_fixed_r.join('') + '</tr>');
  1440. });
  1441. //if(data.length === 0) return;
  1442. that.layBody.scrollTop(0);
  1443. that.layMain.find('.'+ NONE).remove();
  1444. that.layMain.find('tbody').html(trs.join(''));
  1445. that.layFixLeft.find('tbody').html(trs_fixed.join(''));
  1446. that.layFixRight.find('tbody').html(trs_fixed_r.join(''));
  1447. that.renderForm();
  1448. that.syncCheckAll();
  1449. that.haveInit ? that.scrollPatch() : setTimeout(function(){
  1450. that.scrollPatch();
  1451. }, 50);
  1452. that.haveInit = true;
  1453. layer.close(that.tipsIndex);
  1454. };
  1455. that.key = options.id || options.index;
  1456. // table.cache[that.key] = data; //记录数据
  1457. table.setDataList(that.key,data);
  1458. //显示隐藏分页栏
  1459. that.layPage[data.length === 0 && curr == 1 ? 'addClass' : 'removeClass'](HIDE);
  1460. //排序
  1461. if(sort){
  1462. return render();
  1463. }
  1464. if(data.length === 0){
  1465. that.renderForm();
  1466. that.layFixed.remove();
  1467. that.layMain.find('tbody').html('');
  1468. that.layMain.find('.'+ NONE).remove();
  1469. return that.layMain.append('<div class="'+ NONE +'">'+ options.text.none +'</div>');
  1470. }
  1471. render();
  1472. that.renderPage(count);//分页渲染
  1473. //calss加载完成
  1474. table.pushClassIds(options.id,true);
  1475. layui.each(options.cols, function(i1, item1){
  1476. layui.each(item1, function(i2, item2){
  1477. })
  1478. });
  1479. };
  1480. /**
  1481. * 渲染分页
  1482. */
  1483. Class.prototype.renderPage=function (count) {
  1484. var that = this
  1485. ,options = that.config;
  1486. //同步分页状态
  1487. if(options.page){
  1488. options.page = $.extend({
  1489. elem: 'layui-table-page' + options.index
  1490. ,count: count
  1491. ,limit: options.limit
  1492. ,limits: options.limits || [10,15,20,30,40,50,60,70,80,90]
  1493. ,groups: 3
  1494. ,layout: ['prev', 'page', 'next', 'skip', 'count', 'limit']
  1495. ,prev: '<i class="layui-icon">&#xe603;</i>'
  1496. ,next: '<i class="layui-icon">&#xe602;</i>'
  1497. ,jump: function(obj, first){
  1498. if(!first){
  1499. //分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们
  1500. //而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用)
  1501. that.page = obj.curr; //更新页码
  1502. options.limit = obj.limit; //更新每页条数
  1503. that.pullData(obj.curr, that.loading());
  1504. }
  1505. }
  1506. }, options.page);
  1507. options.page.count = count; //更新总条数
  1508. laypage.render(options.page);
  1509. }
  1510. };
  1511. /**
  1512. * 过滤区域的渲染
  1513. */
  1514. Class.prototype.renderFilter = function(){
  1515. var that = this
  1516. ,options = that.config
  1517. ,VIEW_CLASS=ELEM_VIEW
  1518. ,index=that.index; //索引
  1519. var v = [];
  1520. v.push('<form method="post" id="'+options.id+'_filter_form">');
  1521. v.push('<table cellspacing="0" cellpadding="0" border="0" class="layui-table"><thead><tr>');
  1522. layui.each(options.cols,function (i, o) {
  1523. layui.each(o, function(i2, item2){
  1524. var field=item2.field||i2;
  1525. var minW=item2.minWidth?"data-minwidth='"+item2.minWidth+"'":"";
  1526. var rowCols=item2.colspan?'colspan="'+item2.colspan+'"':'';
  1527. var rowspan=item2.rowspan?'rowspan="'+item2.rowspan+'"':'';
  1528. var unresize=item2.unresize?'data-unresize="true"':'';
  1529. v.push('<th data-field="'+field+'"'+minW+rowCols+rowspan +unresize+'>');
  1530. v.push('<div class="layui-table-cell laytable-cell-'+function () {
  1531. var tem="";
  1532. if (item2.colspan > 1) {
  1533. tem='group';
  1534. }else{
  1535. tem=index+"-"+field;
  1536. if(item2.type !== "normal"){
  1537. tem+=" laytable-cell-"+item2.type;
  1538. }
  1539. }
  1540. return tem;
  1541. }()+'">');
  1542. if(!item2.isFilter||!item2.field){//不开启行内过滤或没有列名
  1543. v.push('');
  1544. }else{
  1545. v.push('<input class="layui-input '+ ELEM_EDIT +'" id="filter_'+item2.field+'" name="filter_'+item2.field+'">');
  1546. }
  1547. v.push('</div></th>');
  1548. });
  1549. });
  1550. v.push('</tr></thead></table>');
  1551. v.push('</form>');
  1552. return v.join('');
  1553. };
  1554. //找到对应的列元素
  1555. Class.prototype.getColElem = function(parent, field){
  1556. var that = this
  1557. ,options = that.config;
  1558. return parent.eq(0).find('.laytable-cell-'+ (options.index + '-' + field) + ':eq(0)');
  1559. };
  1560. //渲染表单
  1561. Class.prototype.renderForm = function(type){
  1562. form.render(type, 'LAY-table-'+ this.index);
  1563. }
  1564. //数据排序
  1565. Class.prototype.sort = function(th, type, pull, formEvent){
  1566. var that = this
  1567. ,field
  1568. ,res = {}
  1569. ,options = that.config
  1570. ,filter = options.elem.attr('lay-filter')
  1571. ,data = table.getDataList(that.key), thisData;
  1572. //字段匹配
  1573. if(typeof th === 'string'){
  1574. that.layHeader.find('th').each(function(i, item){
  1575. var othis = $(this)
  1576. ,_field = othis.data('field');
  1577. if(_field === th){
  1578. th = othis;
  1579. field = _field;
  1580. return false;
  1581. }
  1582. });
  1583. }
  1584. try {
  1585. var field = field || th.data('field');
  1586. //如果欲执行的排序已在状态中,则不执行渲染
  1587. if(that.sortKey && !pull){
  1588. if(field === that.sortKey.field && type === that.sortKey.sort){
  1589. return;
  1590. }
  1591. }
  1592. var elemSort = that.layHeader.find('th .laytable-cell-'+ options.index +'-'+ field).find(ELEM_SORT);
  1593. that.layHeader.find('th').find(ELEM_SORT).removeAttr('lay-sort'); //清除其它标题排序状态
  1594. elemSort.attr('lay-sort', type || null);
  1595. that.layFixed.find('th')
  1596. } catch(e){
  1597. return hint.error('Table modules: Did not match to field');
  1598. }
  1599. //记录排序索引和类型
  1600. that.sortKey = {
  1601. field: field
  1602. ,sort: type
  1603. };
  1604. if(type === 'asc'){ //升序
  1605. thisData = layui.sort(data, field);
  1606. } else if(type === 'desc'){ //降序
  1607. thisData = layui.sort(data, field, true);
  1608. } else { //清除排序
  1609. thisData = layui.sort(data, table.config.indexName);
  1610. delete that.sortKey;
  1611. }
  1612. res[options.response.dataName] = thisData;
  1613. that.renderData(res, that.page, that.count, true);
  1614. if(formEvent){
  1615. layui.event.call(th, MOD_NAME, 'sort('+ filter +')', {
  1616. field: field
  1617. ,type: type
  1618. });
  1619. }
  1620. };
  1621. //请求loading
  1622. Class.prototype.loading = function(){
  1623. var that = this
  1624. ,options = that.config;
  1625. if(options.loading && options.url){
  1626. return layer.msg('数据请求中', {
  1627. icon: 16
  1628. ,offset: [
  1629. that.elem.offset().top + that.elem.height()/2 - 35 - _WIN.scrollTop() + 'px'
  1630. ,that.elem.offset().left + that.elem.width()/2 - 90 - _WIN.scrollLeft() + 'px'
  1631. ]
  1632. ,time: -1
  1633. ,anim: -1
  1634. ,fixed: false
  1635. });
  1636. }
  1637. };
  1638. //同步选中值状态
  1639. Class.prototype.setCheckData = function(index, checked){
  1640. var that = this
  1641. ,options = that.config
  1642. ,thisData = table.getDataList(that.key);
  1643. if(!thisData[index]) return;
  1644. if(thisData[index].constructor === Array) return;
  1645. thisData[index][options.checkName] = checked;
  1646. };
  1647. //同步全选按钮状态
  1648. Class.prototype.syncCheckAll = function(){
  1649. var that = this
  1650. ,options = that.config
  1651. ,checkAllElem = that.layHeader.find('input[name="layTableCheckbox"]')
  1652. ,syncColsCheck = function(checked){
  1653. that.eachCols(function(i, item){
  1654. if(item.type === 'checkbox'){
  1655. item[options.checkName] = checked;
  1656. }
  1657. });
  1658. return checked;
  1659. };
  1660. if(!checkAllElem[0]) return;
  1661. if(table.checkStatus(that.key).isAll){
  1662. if(!checkAllElem[0].checked){
  1663. checkAllElem.prop('checked', true);
  1664. that.renderForm('checkbox');
  1665. }
  1666. syncColsCheck(true);
  1667. } else {
  1668. if(checkAllElem[0].checked){
  1669. checkAllElem.prop('checked', false);
  1670. that.renderForm('checkbox');
  1671. }
  1672. syncColsCheck(false);
  1673. }
  1674. };
  1675. //获取cssRule
  1676. Class.prototype.getCssRule = function(field, callback){
  1677. var that = this
  1678. ,style = that.elem.find('style')[0]
  1679. ,sheet = style.sheet || style.styleSheet || {}
  1680. ,rules = sheet.cssRules || sheet.rules;
  1681. layui.each(rules, function(i, item){
  1682. if(item.selectorText === ('.laytable-cell-'+ that.index +'-'+ field)){
  1683. return callback(item), true;
  1684. }
  1685. });
  1686. };
  1687. /**
  1688. * 窗体变化自适应
  1689. */
  1690. Class.prototype.resize = function(){
  1691. var that = this;
  1692. //根据父窗体高度设置table的高度
  1693. // 1、table自身顶级容器高度(layui-table-view)
  1694. // 2、内容区域高度(layui-table-main)
  1695. that.setArea();
  1696. that.fullSize();//高度控制
  1697. //宽度控制(最后一行)
  1698. that.resizeWidth();
  1699. that.scrollPatch();
  1700. };
  1701. /**
  1702. * 重新渲染宽度
  1703. */
  1704. Class.prototype.resizeWidth = function(){
  1705. var that = this;
  1706. that.renderTdCss();
  1707. };
  1708. //铺满表格主体高度
  1709. Class.prototype.fullSize = function(){
  1710. var that = this
  1711. ,options = that.config
  1712. ,height = options.height, bodyHeight;
  1713. height = that.getParentDivHeight(options.id) - that.fullHeightGap;
  1714. height = '100%';
  1715. that.elem.css('height', height);
  1716. //tbody区域高度
  1717. // bodyHeight = parseFloat(height) - parseFloat(that.layHeader.height()) - 1;//原本代码
  1718. var theader=options.isFilter?76:38;//没有行内过滤区域
  1719. bodyHeight = parseFloat(height) - theader - 1;//###注意:现在写死表头固定高度为38px,即不支持多表头方式(在tab方式下无法获取正确的高度,待处理)
  1720. if(options.toolbar){
  1721. bodyHeight = bodyHeight - that.layTool.outerHeight();
  1722. }
  1723. if(options.page){
  1724. bodyHeight = bodyHeight - that.layPage.outerHeight() - 1;
  1725. }
  1726. // that.layMain.css('height', bodyHeight);
  1727. // console.log(bodyHeight,that.layHeader.height());
  1728. };
  1729. //获取滚动条宽度
  1730. Class.prototype.getScrollWidth = function(elem){
  1731. var width = 0;
  1732. if(elem){
  1733. width = elem.offsetWidth - elem.clientWidth;
  1734. } else {
  1735. elem = document.createElement('div');
  1736. elem.style.width = '100px';
  1737. elem.style.height = '100px';
  1738. elem.style.overflowY = 'scroll';
  1739. document.body.appendChild(elem);
  1740. width = elem.offsetWidth - elem.clientWidth;
  1741. document.body.removeChild(elem);
  1742. }
  1743. return width;
  1744. };
  1745. //滚动条补丁
  1746. Class.prototype.scrollPatch = function(){
  1747. var that = this
  1748. ,layMainTable = that.layMain.children('table')
  1749. ,scollWidth = that.layMain.width() - that.layMain.prop('clientWidth') //纵向滚动条宽度
  1750. ,scollHeight = that.layMain.height() - that.layMain.prop('clientHeight') //横向滚动条高度
  1751. ,getScrollWidth = that.getScrollWidth(that.layMain[0]) //获取主容器滚动条宽度,如果有的话
  1752. ,outWidth = layMainTable.outerWidth() - that.layMain.width(); //表格内容器的超出宽度
  1753. //如果存在自动列宽,则要保证绝对填充满,并且不能出现横向滚动条
  1754. if(that.autoColNums && outWidth < 5 && !that.scrollPatchWStatus){
  1755. var th = that.layHeader.eq(0).find('thead th:last-child')
  1756. ,field = th.data('field');
  1757. that.getCssRule(field, function(item){
  1758. var width = item.style.width || th.outerWidth();
  1759. item.style.width = (parseFloat(width) - getScrollWidth - outWidth) + 'px';
  1760. //二次校验,如果仍然出现横向滚动条
  1761. if(that.layMain.height() - that.layMain.prop('clientHeight') > 0){
  1762. item.style.width = parseFloat(item.style.width) - 1 + 'px';
  1763. }
  1764. that.scrollPatchWStatus = true;
  1765. });
  1766. }
  1767. if(scollWidth && scollHeight){
  1768. if(that.elem.find('.layui-table-patch').length<=0){
  1769. var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
  1770. patchElem.find('div').css({
  1771. width: scollWidth
  1772. });
  1773. that.layHeader.eq(0).find('thead tr').append(patchElem);
  1774. //that.layFilter.find('table thead tr').append(patchElem);
  1775. }
  1776. } else {
  1777. that.layFilter.eq(0).find('.layui-table-patch').remove();
  1778. that.layHeader.eq(0).find('.layui-table-patch').remove();
  1779. }
  1780. //固定列区域高度
  1781. var mainHeight = that.layMain.height()
  1782. ,fixHeight = mainHeight - scollHeight;
  1783. that.layFixed.find(ELEM_BODY).css('height', layMainTable.height() > fixHeight ? fixHeight : 'auto');
  1784. //表格宽度小于容器宽度时,隐藏固定列
  1785. that.layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
  1786. //操作栏
  1787. that.layFixRight.css('right', scollWidth - 1);
  1788. };
  1789. //事件处理
  1790. Class.prototype.events = function(){
  1791. var that = this
  1792. ,options = that.config
  1793. ,_BODY = $('body')
  1794. ,dict = {}
  1795. ,th = that.layHeader.find('th')
  1796. ,resizing
  1797. ,ELEM_CELL = '.layui-table-cell'
  1798. ,filter = options.elem.attr('lay-filter')
  1799. ,layFilter=that.layFilter.find("[name^='filter_']")//行内过滤元素
  1800. ;
  1801. //行内过滤
  1802. layFilter.on('keyup',function () {
  1803. that.page=1;
  1804. that.pullData(that.page, that.loading());
  1805. });
  1806. //拖拽调整宽度
  1807. th.on('mousemove', function(e){
  1808. var othis = $(this)
  1809. ,oLeft = othis.offset().left
  1810. ,pLeft = e.clientX - oLeft;
  1811. if(othis.attr('colspan') > 1 || othis.data('unresize') || dict.resizeStart){
  1812. return;
  1813. }
  1814. dict.allowResize = othis.width() - pLeft <= 10; //是否处于拖拽允许区域
  1815. _BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
  1816. }).on('mouseleave', function(){
  1817. var othis = $(this);
  1818. if(dict.resizeStart) return;
  1819. _BODY.css('cursor', '');
  1820. }).on('mousedown', function(e){
  1821. var othis = $(this);
  1822. if(dict.allowResize){
  1823. var field = othis.data('field');
  1824. e.preventDefault();
  1825. dict.resizeStart = true; //开始拖拽
  1826. dict.offset = [e.clientX, e.clientY]; //记录初始坐标
  1827. that.getCssRule(field, function(item){
  1828. var width = item.style.width || othis.outerWidth();
  1829. dict.rule = item;
  1830. dict.ruleWidth = parseFloat(width);
  1831. dict.minWidth = othis.data('minwidth') || options.cellMinWidth;
  1832. });
  1833. }
  1834. });
  1835. //拖拽中
  1836. _DOC.on('mousemove', function(e){
  1837. if(dict.resizeStart){
  1838. e.preventDefault();
  1839. if(dict.rule){
  1840. var setWidth = dict.ruleWidth + e.clientX - dict.offset[0];
  1841. if(setWidth < dict.minWidth) setWidth = dict.minWidth;
  1842. dict.rule.style.width = setWidth + 'px';
  1843. layer.close(that.tipsIndex);
  1844. }
  1845. resizing = 1
  1846. }
  1847. }).on('mouseup', function(e){
  1848. if(dict.resizeStart){
  1849. dict = {};
  1850. _BODY.css('cursor', '');
  1851. that.scrollPatch();
  1852. }
  1853. if(resizing === 2){
  1854. resizing = null;
  1855. }
  1856. });
  1857. //排序
  1858. th.on('click', function(){
  1859. var othis = $(this)
  1860. ,elemSort = othis.find(ELEM_SORT)
  1861. ,nowType = elemSort.attr('lay-sort')
  1862. ,type;
  1863. if(!elemSort[0] || resizing === 1) return resizing = 2;
  1864. if(nowType === 'asc'){
  1865. type = 'desc';
  1866. } else if(nowType === 'desc'){
  1867. type = null;
  1868. } else {
  1869. type = 'asc';
  1870. }
  1871. that.sort(othis, type, null, true);
  1872. }).find(ELEM_SORT+' .layui-edge ').on('click', function(e){
  1873. var othis = $(this)
  1874. ,index = othis.index()
  1875. ,field = othis.parents('th').eq(0).data('field')
  1876. layui.stope(e);
  1877. if(index === 0){
  1878. that.sort(field, 'asc', null, true);
  1879. } else {
  1880. that.sort(field, 'desc', null, true);
  1881. }
  1882. });
  1883. /**
  1884. * 树形节点点击事件(隐藏展开下级节点)
  1885. */
  1886. that.elem.on('click', 'i.layui-tree-head', function(){
  1887. var othis = $(this)
  1888. ,index = othis.parents('tr').eq(0).data('index')
  1889. ,tr = that.layBody.find('tr[data-index="'+ index +'"]')
  1890. ,options=that.config
  1891. ,tree_id=options[TREE_ID]
  1892. ,datas=table.getDataList(that.key);//数据
  1893. var o=datas[index];
  1894. that.treeNodeOpen(o,!o.is_open);
  1895. });
  1896. //复选框选择
  1897. that.elem.on('click', 'input[name="layTableCheckbox"]+', function(){
  1898. var checkbox = $(this).prev()
  1899. ,childs = that.layBody.find('input[name="layTableCheckbox"]')
  1900. ,index = checkbox.parents('tr').eq(0).data('index')
  1901. ,checked = checkbox[0].checked
  1902. ,isAll = checkbox.attr('lay-filter') === 'layTableAllChoose';
  1903. //全选
  1904. if(isAll){
  1905. childs.each(function(i, item){
  1906. item.checked = checked;
  1907. that.setCheckData(i, checked);
  1908. });
  1909. that.syncCheckAll();
  1910. that.renderForm('checkbox');
  1911. } else {
  1912. that.setCheckData(index, checked);
  1913. that.syncCheckAll();
  1914. }
  1915. layui.event.call(this, MOD_NAME, 'checkbox('+ filter +')', {
  1916. checked: checked
  1917. ,data: table.getDataList(that.key) ? (table.getDataList(that.key)[index] || {}) : {}
  1918. ,type: isAll ? 'all' : 'one'
  1919. });
  1920. });
  1921. //行事件
  1922. that.layBody.on('mouseenter', 'tr', function(){
  1923. var othis = $(this)
  1924. ,index = othis.index();
  1925. that.layBody.find('tr:eq('+ index +')').addClass(ELEM_HOVER)
  1926. })
  1927. that.layBody.on('mouseleave', 'tr', function(){
  1928. var othis = $(this)
  1929. ,index = othis.index();
  1930. that.layBody.find('tr:eq('+ index +')').removeClass(ELEM_HOVER)
  1931. });
  1932. //单元格编辑
  1933. that.layBody.on('change', '.'+ELEM_EDIT, function(){
  1934. var othis = $(this)
  1935. ,value = this.value
  1936. ,field = othis.parent().data('field')
  1937. ,index = othis.parents('tr').eq(0).data('index')
  1938. ,data = table.getDataList(that.key)[index];
  1939. data[field] = value; //更新缓存中的值
  1940. layui.event.call(this, MOD_NAME, 'edit('+ filter +')', {
  1941. value: value
  1942. ,data: data
  1943. ,field: field
  1944. });
  1945. });
  1946. that.layBody.on('blur', '.'+ELEM_EDIT, function(){//单元格失去焦点
  1947. var templet
  1948. ,othis = $(this)
  1949. ,field = othis.parent().data('field')
  1950. ,index = othis.parents('tr').eq(0).data('index')
  1951. ,editType = othis.parent().data('edit')
  1952. ,data = table.getDataList(that.key)[index];
  1953. var options = that.config;
  1954. that.eachCols(function(i, item){
  1955. if(item.field == field && item.templet){
  1956. templet = item.templet;
  1957. }
  1958. });
  1959. var value="";
  1960. if(editType === 'select') { //选择框
  1961. var rowsField=dl.ui.table.drop.findFieldObj(options.cols[0],field);
  1962. if(rowsField&&rowsField['drop']){
  1963. var o=dl.cache.code.get(rowsField.drop);
  1964. value=dl.ui.table.drop.findDropLable(rowsField.drop,this.value);
  1965. }
  1966. othis.parent().find(ELEM_CELL+' p').html(
  1967. templet ? laytpl($(templet).html() || value).render(data) : value
  1968. );
  1969. } else {//输入框
  1970. othis.parent().find(ELEM_CELL+' p').html(
  1971. templet ? laytpl($(templet).html() || this.value).render(data) : this.value
  1972. );
  1973. }
  1974. othis.parent().data('content', this.value);
  1975. othis.remove();
  1976. });
  1977. //单元格事件
  1978. that.layBody.on('click', 'td div.layui-table-cell p', function(){
  1979. var othis = $(this).parent().parent()
  1980. ,field = othis.data('field')
  1981. ,editType = othis.data('edit')
  1982. ,index = othis.parents('tr').eq(0).data('index')
  1983. ,data = table.getDataList(that.key)[index]
  1984. ,elemCell = othis.children(ELEM_CELL);
  1985. var options = that.config;
  1986. layer.close(that.tipsIndex);
  1987. if(othis.data('off')) return;
  1988. //显示编辑表单
  1989. if(editType){
  1990. if(editType === 'select') { //选择框
  1991. var dropName=othis.data('drop');
  1992. var rowsField=dl.ui.table.drop.findFieldObj(options.cols[0],field);
  1993. var o=dl.cache.code.get(rowsField.drop);
  1994. var html='';
  1995. var scv=o.syscodevaluecache;
  1996. for(var i in scv){
  1997. var isSelected="";
  1998. if(scv[i].scv_value==data[field]){
  1999. isSelected="selected='selected'";
  2000. }
  2001. //选中
  2002. html+='<option '+isSelected+' value="'+scv[i].scv_value+'">'+scv[i].scv_show_name+'</option>'
  2003. }
  2004. var select = $('<select class="'+ ELEM_EDIT +'" lay-ignore>' +
  2005. html+
  2006. '</select>');
  2007. othis.find('.'+ELEM_EDIT)[0] || othis.append(select);
  2008. } else { //输入框
  2009. var input = $('<input class="layui-input '+ ELEM_EDIT +'">');
  2010. input[0].value = $.trim($(this).text());// othis.data('content') || elemCell.text();
  2011. othis.find('.'+ELEM_EDIT)[0] || othis.append(input);
  2012. input.focus();
  2013. }
  2014. return;
  2015. }
  2016. //如果出现省略,则可查看更多
  2017. if(elemCell.find('.layui-form-switch,.layui-form-checkbox')[0]) return; //限制不出现更多(暂时)
  2018. if(Math.round(elemCell.prop('scrollWidth')) > Math.round(elemCell.outerWidth())){
  2019. that.tipsIndex = layer.tips([
  2020. '<div class="layui-table-tips-main" style="margin-top: -'+ (elemCell.height() + 16) +'px;'+ function(){
  2021. if(options.size === 'sm'){
  2022. return 'padding: 4px 15px; font-size: 12px;';
  2023. }
  2024. if(options.size === 'lg'){
  2025. return 'padding: 14px 15px;';
  2026. }
  2027. return '';
  2028. }() +'">'
  2029. ,elemCell.html()
  2030. ,'</div>'
  2031. ,'<i class="layui-icon layui-table-tips-c">&#x1006;</i>'
  2032. ].join(''), elemCell[0], {
  2033. tips: [3, '']
  2034. ,time: -1
  2035. ,anim: -1
  2036. ,maxWidth: (device.ios || device.android) ? 300 : 600
  2037. ,isOutAnim: false
  2038. ,skin: 'layui-table-tips'
  2039. ,success: function(layero, index){
  2040. layero.find('.layui-table-tips-c').on('click', function(){
  2041. layer.close(index);
  2042. });
  2043. }
  2044. });
  2045. }
  2046. });
  2047. //工具条操作事件
  2048. that.layBody.on('click', '*[lay-event]', function(){
  2049. var othis = $(this)
  2050. ,index = othis.parents('tr').eq(0).data('index')
  2051. ,tr = that.layBody.find('tr[data-index="'+ index +'"]')
  2052. ,ELEM_CLICK = 'layui-table-click'
  2053. ,list = table.getDataList(that.key)
  2054. ,data = table.getDataList(that.key)[index];
  2055. layui.event.call(this, MOD_NAME, 'tool('+ filter +')', {
  2056. data: data//table.clearCacheKey(data)
  2057. ,event: othis.attr('lay-event')
  2058. ,tr: tr
  2059. ,del: function(){
  2060. table.delRow(options.id,data);
  2061. }
  2062. ,update: function(fields){
  2063. fields = fields || {};
  2064. layui.each(fields, function(key, value){
  2065. if(key in data){
  2066. var templet, td = tr.children('td[data-field="'+ key +'"]');
  2067. data[key] = value;
  2068. that.eachCols(function(i, item2){
  2069. if(item2.field == key && item2.templet){
  2070. templet = item2.templet;
  2071. }
  2072. });
  2073. td.children(ELEM_CELL).html(
  2074. templet ? laytpl($(templet).html() || value).render(data) : value
  2075. );
  2076. td.data('content', value);
  2077. }
  2078. });
  2079. }
  2080. });
  2081. tr.addClass(ELEM_CLICK).siblings('tr').removeClass(ELEM_CLICK);
  2082. });
  2083. //同步滚动条
  2084. that.layMain.on('scroll', function(){
  2085. var othis = $(this)
  2086. ,scrollLeft = othis.scrollLeft()
  2087. ,scrollTop = othis.scrollTop();
  2088. that.layHeader.scrollLeft(scrollLeft);
  2089. that.layFixed.find(ELEM_BODY).scrollTop(scrollTop);
  2090. layer.close(that.tipsIndex);
  2091. });
  2092. _WIN.on('resize', function(){ //自适应
  2093. that.resize();
  2094. });
  2095. };
  2096. //表格重载
  2097. thisTable.config = {};
  2098. //自动完成渲染
  2099. table.init();
  2100. // layui.link("//" + location.host + '/js/layuiPlugins/treeGrid.css');//引入css
  2101. exports(MOD_NAME, table);
  2102. });