/
table.js
2031 lines (1744 loc) · 66.5 KB
/
table.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* layui.table
* 数据表格组件
*/
layui.define(['laytpl', 'laypage', 'layer', 'form', 'util'], function(exports){
"use strict";
var $ = layui.$
,laytpl = layui.laytpl
,laypage = layui.laypage
,layer = layui.layer
,form = layui.form
,util = layui.util
,hint = layui.hint()
,device = layui.device()
//外部接口
,table = {
config: {
checkName: 'LAY_CHECKED' //是否选中状态的字段名
,indexName: 'LAY_TABLE_INDEX' //初始下标索引名,用于恢复排序
} //全局配置项
,cache: {} //数据缓存
,index: layui.table ? (layui.table.index + 10000) : 0
//设置全局项
,set: function(options){
var that = this;
that.config = $.extend({}, that.config, options);
return that;
}
//事件
,on: function(events, callback){
return layui.onevent.call(this, MOD_NAME, events, callback);
}
}
//操作当前实例
,thisTable = function(){
var that = this
,options = that.config
,id = options.id || options.index;
if(id){
thisTable.that[id] = that; //记录当前实例对象
thisTable.config[id] = options; //记录当前实例配置项
}
return {
config: options
,reload: function(options, deep){
that.reload.call(that, options, deep);
}
,setColsWidth: function(){
that.setColsWidth.call(that);
}
,resize: function(){ //重置表格尺寸/结构
that.resize.call(that);
}
}
}
//获取当前实例配置项
,getThisTableConfig = function(id){
var config = thisTable.config[id];
if(!config) hint.error(id ? ('The table instance with ID \''+ id +'\' not found') : 'ID argument required');
return config || null;
}
//解析自定义模板数据
,parseTempData = function(item3, content, tplData, text){ //表头数据、原始内容、表体数据、是否只返回文本
var str = item3.templet ? function(){
return typeof item3.templet === 'function'
? item3.templet(tplData)
: laytpl($(item3.templet).html() || String(content)).render(tplData)
}() : content;
return text ? $('<div>'+ str +'</div>').text() : str;
}
//字符常量
,MOD_NAME = 'table', ELEM = '.layui-table', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled', NONE = 'layui-none'
,ELEM_VIEW = 'layui-table-view', ELEM_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'
//thead区域模板
,TPL_HEADER = function(options){
var rowCols = '{{#if(item2.colspan){}} colspan="{{item2.colspan}}"{{#} if(item2.rowspan){}} rowspan="{{item2.rowspan}}"{{#}}}';
options = options || {};
return ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
,'<thead>'
,'{{# layui.each(d.data.cols, function(i1, item1){ }}'
,'<tr>'
,'{{# layui.each(item1, function(i2, item2){ }}'
,'{{# if(item2.fixed && item2.fixed !== "right"){ left = true; } }}'
,'{{# if(item2.fixed === "right"){ right = true; } }}'
,function(){
if(options.fixed && options.fixed !== 'right'){
return '{{# if(item2.fixed && item2.fixed !== "right"){ }}';
}
if(options.fixed === 'right'){
return '{{# if(item2.fixed === "right"){ }}';
}
return '';
}()
,'{{# var isSort = !(item2.colGroup) && item2.sort; }}'
,'<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{{# } }}">'
,'<div class="layui-table-cell laytable-cell-'
,'{{# if(item2.colGroup){ }}'
,'group'
,'{{# } else { }}'
,'{{d.index}}-{{i1}}-{{i2}}'
,'{{# if(item2.type !== "normal"){ }}'
,' laytable-cell-{{ item2.type }}'
,'{{# } }}'
,'{{# } }}'
,'" {{#if(item2.align){}}align="{{item2.align}}"{{#}}}>'
,'{{# if(item2.type === "checkbox"){ }}' //复选框
,'<input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose" {{# if(item2[d.data.checkName]){ }}checked{{# }; }}>'
,'{{# } else { }}'
,'<span>{{item2.title||""}}</span>'
,'{{# if(isSort){ }}'
,'<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>'
,'{{# } }}'
,'{{# } }}'
,'</div>'
,'</th>'
,(options.fixed ? '{{# }; }}' : '')
,'{{# }); }}'
,'</tr>'
,'{{# }); }}'
,'</thead>'
,'</table>'].join('');
}
//tbody区域模板
,TPL_BODY = ['<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
,'<tbody></tbody>'
,'</table>'].join('')
//主模板
,TPL_MAIN = ['<div class="layui-form layui-border-box {{d.VIEW_CLASS}}{{# if(d.data.className){ }} {{ d.data.className }}{{# } }}" 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;{{# } }}">'
,'{{# if(d.data.toolbar){ }}'
,'<div class="layui-table-tool">'
,'<div class="layui-table-tool-temp"></div>'
,'<div class="layui-table-tool-self"></div>'
,'</div>'
,'{{# } }}'
,'<div class="layui-table-box">'
,'{{# if(d.data.loading){ }}'
,'<div class="layui-table-init" style="background-color: #fff;">'
,'<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>'
,'</div>'
,'{{# } }}'
,'{{# var left, right; }}'
,'<div class="layui-table-header">'
,TPL_HEADER()
,'</div>'
,'<div class="layui-table-body layui-table-main">'
,TPL_BODY
,'</div>'
,'{{# if(left){ }}'
,'<div class="layui-table-fixed layui-table-fixed-l">'
,'<div class="layui-table-header">'
,TPL_HEADER({fixed: true})
,'</div>'
,'<div class="layui-table-body">'
,TPL_BODY
,'</div>'
,'</div>'
,'{{# }; }}'
,'{{# if(right){ }}'
,'<div class="layui-table-fixed layui-table-fixed-r">'
,'<div class="layui-table-header">'
,TPL_HEADER({fixed: 'right'})
,'<div class="layui-table-mend"></div>'
,'</div>'
,'<div class="layui-table-body">'
,TPL_BODY
,'</div>'
,'</div>'
,'{{# }; }}'
,'</div>'
,'{{# if(d.data.totalRow){ }}'
,'<div class="layui-table-total">'
,'<table cellspacing="0" cellpadding="0" border="0" class="layui-table" '
,'{{# if(d.data.skin){ }}lay-skin="{{d.data.skin}}"{{# } }} {{# if(d.data.size){ }}lay-size="{{d.data.size}}"{{# } }} {{# if(d.data.even){ }}lay-even{{# } }}>'
,'<tbody><tr><td><div class="layui-table-cell" style="visibility: hidden;">Total</div></td></tr></tbody>'
, '</table>'
,'</div>'
,'{{# } }}'
,'{{# if(d.data.page){ }}'
,'<div class="layui-table-page">'
,'<div id="layui-table-page{{d.index}}"></div>'
,'</div>'
,'{{# } }}'
,'<style>'
,'{{# layui.each(d.data.cols, function(i1, item1){'
,'layui.each(item1, function(i2, item2){ }}'
,'.laytable-cell-{{d.index}}-{{i1}}-{{i2}}{ '
,'{{# if(item2.width){ }}'
,'width: {{item2.width}}px;'
,'{{# } }}'
,' }'
,'{{# });'
,'}); }}'
,'</style>'
,'</div>'].join('')
,_WIN = $(window)
,_DOC = $(document)
//构造器
,Class = function(options){
var that = this;
that.index = ++table.index;
that.config = $.extend({}, that.config, table.config, options);
that.render();
};
//初始默认配置
Class.prototype.config = {
limit: 10 //每页显示的数量
,loading: true //请求数据时,是否显示 loading
,cellMinWidth: 60 //所有单元格默认最小宽度
,defaultToolbar: ['filter', 'exports', 'print'] //工具栏右侧图标
,autoSort: true //是否前端自动排序。如果否,则需自主排序(通常为服务端处理好排序)
,text: {
none: '无数据'
}
};
//表格渲染
Class.prototype.render = function(){
var that = this
,options = that.config;
options.elem = $(options.elem);
options.where = options.where || {};
options.id = options.id || options.elem.attr('id') || that.index;
//请求参数的自定义格式
options.request = $.extend({
pageName: 'page'
,limitName: 'limit'
}, options.request)
//响应数据的自定义格式
options.response = $.extend({
statusName: 'code' //规定数据状态的字段名称
,statusCode: 0 //规定成功的状态码
,msgName: 'msg' //规定状态信息的字段名称
,dataName: 'data' //规定数据总数的字段名称
,totalRowName: 'totalRow' //规定数据统计的字段名称
,countName: 'count'
}, options.response);
//如果 page 传入 laypage 对象
if(typeof options.page === 'object'){
options.limit = options.page.limit || options.limit;
options.limits = options.page.limits || options.limits;
that.page = options.page.curr = options.page.curr || 1;
delete options.page.elem;
delete options.page.jump;
}
if(!options.elem[0]) return that;
//高度铺满:full-差距值
if(options.height && /^full-\d+$/.test(options.height)){
that.fullHeightGap = options.height.split('-')[1];
options.height = _WIN.height() - that.fullHeightGap;
}
//初始化一些参数
that.setInit();
//开始插入替代元素
var othis = options.elem
,hasRender = othis.next('.' + ELEM_VIEW)
//主容器
,reElem = that.elem = $(laytpl(TPL_MAIN).render({
VIEW_CLASS: ELEM_VIEW
,data: options
,index: that.index //索引
}));
options.index = that.index;
that.key = options.id || options.index;
//生成替代元素
hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender
othis.after(reElem);
//各级容器
that.layTool = reElem.find(ELEM_TOOL);
that.layBox = reElem.find(ELEM_BOX);
that.layHeader = reElem.find(ELEM_HEADER);
that.layMain = reElem.find(ELEM_MAIN);
that.layBody = reElem.find(ELEM_BODY);
that.layFixed = reElem.find(ELEM_FIXED);
that.layFixLeft = reElem.find(ELEM_FIXL);
that.layFixRight = reElem.find(ELEM_FIXR);
that.layTotal = reElem.find(ELEM_TOTAL);
that.layPage = reElem.find(ELEM_PAGE);
//初始化工具栏
that.renderToolbar();
//让表格平铺
that.fullSize();
//如果多级表头,则填补表头高度
if(options.cols.length > 1){
//补全高度
var th = that.layFixed.find(ELEM_HEADER).find('th');
th.height(that.layHeader.height() - 1 - parseFloat(th.css('padding-top')) - parseFloat(th.css('padding-bottom')));
}
that.pullData(that.page); //请求数据
that.events(); //事件
};
//根据列类型,定制化参数
Class.prototype.initOpts = function(item){
var that = this
,options = that.config
,initWidth = {
checkbox: 48
,radio: 48
,space: 15
,numbers: 40
};
//让 type 参数兼容旧版本
if(item.checkbox) item.type = "checkbox";
if(item.space) item.type = "space";
if(!item.type) item.type = "normal";
if(item.type !== "normal"){
item.unresize = true;
item.width = item.width || initWidth[item.type];
}
};
//初始化一些参数
Class.prototype.setInit = function(type){
var that = this
,options = that.config;
options.clientWidth = options.width || function(){ //获取容器宽度
//如果父元素宽度为0(一般为隐藏元素),则继续查找上层元素,直到找到真实宽度为止
var getWidth = function(parent){
var width, isNone;
parent = parent || options.elem.parent()
width = parent.width();
try {
isNone = parent.css('display') === 'none';
} catch(e){}
if(parent[0] && (!width || isNone)) return getWidth(parent.parent());
return width;
};
return getWidth();
}();
if(type === 'width') return options.clientWidth;
//初始化列参数
layui.each(options.cols, function(i1, item1){
layui.each(item1, function(i2, item2){
//如果列参数为空,则移除
if(!item2){
item1.splice(i2, 1);
return;
}
item2.key = i1 + '-' + i2;
item2.hide = item2.hide || false;
//设置列的父列索引
//如果是组合列,则捕获对应的子列
if(item2.colGroup || item2.colspan > 1){
var childIndex = 0;
layui.each(options.cols[i1 + 1], function(i22, item22){
//如果子列已经被标注为{HAS_PARENT},或者子列累计 colspan 数等于父列定义的 colspan,则跳出当前子列循环
if(item22.HAS_PARENT || (childIndex > 1 && childIndex == item2.colspan)) return;
item22.HAS_PARENT = true;
item22.parentKey = i1 + '-' + i2;
childIndex = childIndex + parseInt(item22.colspan > 1 ? item22.colspan : 1);
});
item2.colGroup = true; //标注是组合列
}
//根据列类型,定制化参数
that.initOpts(item2);
});
});
};
//初始工具栏
Class.prototype.renderToolbar = function(){
var that = this
,options = that.config
//添加工具栏左侧模板
var leftDefaultTemp = [
'<div class="layui-inline" lay-event="add"><i class="layui-icon layui-icon-add-1"></i></div>'
,'<div class="layui-inline" lay-event="update"><i class="layui-icon layui-icon-edit"></i></div>'
,'<div class="layui-inline" lay-event="delete"><i class="layui-icon layui-icon-delete"></i></div>'
].join('')
,elemToolTemp = that.layTool.find('.layui-table-tool-temp');
if(options.toolbar === 'default'){
elemToolTemp.html(leftDefaultTemp);
} else if(typeof options.toolbar === 'string'){
var toolbarHtml = $(options.toolbar).html() || '';
toolbarHtml && elemToolTemp.html(
laytpl(toolbarHtml).render(options)
);
}
//添加工具栏右侧面板
var layout = {
filter: {
title: '筛选列'
,layEvent: 'LAYTABLE_COLS'
,icon: 'layui-icon-cols'
}
,exports: {
title: '导出'
,layEvent: 'LAYTABLE_EXPORT'
,icon: 'layui-icon-export'
}
,print: {
title: '打印'
,layEvent: 'LAYTABLE_PRINT'
,icon: 'layui-icon-print'
}
}, iconElem = [];
if(typeof options.defaultToolbar === 'object'){
layui.each(options.defaultToolbar, function(i, item){
var thisItem = typeof item === 'string' ? layout[item] : item;
if(thisItem){
iconElem.push('<div class="layui-inline" title="'+ thisItem.title +'" lay-event="'+ thisItem.layEvent +'">'
+'<i class="layui-icon '+ thisItem.icon +'"></i>'
+'</div>');
}
});
}
that.layTool.find('.layui-table-tool-self').html(iconElem.join(''));
}
//同步表头父列的相关值
Class.prototype.setParentCol = function(hide, parentKey){
var that = this
,options = that.config
,parentTh = that.layHeader.find('th[data-key="'+ options.index +'-'+ parentKey +'"]') //获取父列元素
,parentColspan = parseInt(parentTh.attr('colspan')) || 0;
if(parentTh[0]){
var arrParentKey = parentKey.split('-')
,getThisCol = options.cols[arrParentKey[0]][arrParentKey[1]];
hide ? parentColspan-- : parentColspan++;
parentTh.attr('colspan', parentColspan);
parentTh[parentColspan < 1 ? 'addClass' : 'removeClass'](HIDE);
getThisCol.colspan = parentColspan; //同步 colspan 参数
getThisCol.hide = parentColspan < 1; //同步 hide 参数
//递归,继续往上查询是否有父列
var nextParentKey = parentTh.data('parentkey');
nextParentKey && that.setParentCol(hide, nextParentKey);
}
};
//多级表头补丁
Class.prototype.setColsPatch = function(){
var that = this
,options = that.config
//同步表头父列的相关值
layui.each(options.cols, function(i1, item1){
layui.each(item1, function(i2, item2){
if(item2.hide){
that.setParentCol(item2.hide, item2.parentKey);
}
});
});
};
//动态分配列宽
Class.prototype.setColsWidth = function(){
var that = this
,options = that.config
,colNums = 0 //列个数
,autoColNums = 0 //自动列宽的列个数
,autoWidth = 0 //自动列分配的宽度
,countWidth = 0 //所有列总宽度和
,cntrWidth = that.setInit('width');
//统计列个数
that.eachCols(function(i, item){
item.hide || colNums++;
});
//减去边框差和滚动条宽
cntrWidth = cntrWidth - function(){
return (options.skin === 'line' || options.skin === 'nob') ? 2 : colNums + 1;
}() - that.getScrollWidth(that.layMain[0]) - 1;
//计算自动分配的宽度
var getAutoWidth = function(back){
//遍历所有列
layui.each(options.cols, function(i1, item1){
layui.each(item1, function(i2, item2){
var width = 0
,minWidth = item2.minWidth || options.cellMinWidth; //最小宽度
if(!item2){
item1.splice(i2, 1);
return;
}
if(item2.colGroup || item2.hide) return;
if(!back){
width = item2.width || 0;
if(/\d+%$/.test(width)){ //列宽为百分比
width = Math.floor((parseFloat(width) / 100) * cntrWidth);
width < minWidth && (width = minWidth);
} else if(!width){ //列宽未填写
item2.width = width = 0;
autoColNums++;
}
} else if(autoWidth && autoWidth < minWidth){
autoColNums--;
width = minWidth;
}
if(item2.hide) width = 0;
countWidth = countWidth + width;
});
});
//如果未填充满,则将剩余宽度平分
(cntrWidth > countWidth && autoColNums) && (
autoWidth = (cntrWidth - countWidth) / autoColNums
);
}
getAutoWidth();
getAutoWidth(true); //重新检测分配的宽度是否低于最小列宽
//记录自动列数
that.autoColNums = autoColNums;
//设置列宽
that.eachCols(function(i3, item3){
var minWidth = item3.minWidth || options.cellMinWidth;
if(item3.colGroup || item3.hide) return;
//给位分配宽的列平均分配宽
if(item3.width === 0){
that.getCssRule(options.index +'-'+ item3.key, function(item){
item.style.width = Math.floor(autoWidth >= minWidth ? autoWidth : minWidth) + 'px';
});
}
//给设定百分比的列分配列宽
else if(/\d+%$/.test(item3.width)){
that.getCssRule(options.index +'-'+ item3.key, function(item){
item.style.width = Math.floor((parseFloat(item3.width) / 100) * cntrWidth) + 'px';
});
}
});
//填补 Math.floor 造成的数差
var patchNums = that.layMain.width() - that.getScrollWidth(that.layMain[0])
- that.layMain.children('table').outerWidth();
if(that.autoColNums && patchNums >= -colNums && patchNums <= colNums){
var getEndTh = function(th){
var field;
th = th || that.layHeader.eq(0).find('thead th:last-child')
field = th.data('field');
if(!field && th.prev()[0]){
return getEndTh(th.prev())
}
return th
}
,th = getEndTh()
,key = th.data('key');
that.getCssRule(key, function(item){
var width = item.style.width || th.outerWidth();
item.style.width = (parseFloat(width) + patchNums) + 'px';
//二次校验,如果仍然出现横向滚动条(通常是 1px 的误差导致)
if(that.layMain.height() - that.layMain.prop('clientHeight') > 0){
item.style.width = (parseFloat(item.style.width) - 1) + 'px';
}
});
}
that.loading(!0);
};
//重置表格尺寸/结构
Class.prototype.resize = function(){
var that = this;
that.fullSize(); //让表格铺满
that.setColsWidth(); //自适应列宽
that.scrollPatch(); //滚动条补丁
};
//表格重载
Class.prototype.reload = function(options, deep){
var that = this;
options = options || {};
delete that.haveInit;
//防止数组深度合并
layui.each(options, function(key, item){
if(layui._typeof(item) === 'array') delete that.config[key];
});
//对参数进行深度或浅扩展
that.config = $.extend(deep, {}, that.config, options);
//执行渲染
that.render();
};
//异常提示
Class.prototype.errorView = function(html){
var that = this
,elemNone = that.layMain.find('.'+ NONE)
,layNone = $('<div class="'+ NONE +'">'+ (html || 'Error') +'</div>');
if(elemNone[0]){
that.layNone.remove();
elemNone.remove();
}
that.layFixed.addClass(HIDE);
that.layMain.find('tbody').html('');
that.layMain.append(that.layNone = layNone);
table.cache[that.key] = []; //格式化缓存数据
};
//页码
Class.prototype.page = 1;
//获得数据
Class.prototype.pullData = function(curr){
var that = this
,options = that.config
,request = options.request
,response = options.response
,sort = function(){
if(typeof options.initSort === 'object'){
that.sort(options.initSort.field, options.initSort.type);
}
};
that.startTime = new Date().getTime(); //渲染开始时间
if(options.url){ //Ajax请求
var params = {};
params[request.pageName] = curr;
params[request.limitName] = options.limit;
//参数
var data = $.extend(params, options.where);
if(options.contentType && options.contentType.indexOf("application/json") == 0){ //提交 json 格式
data = JSON.stringify(data);
}
that.loading();
$.ajax({
type: options.method || 'get'
,url: options.url
,contentType: options.contentType
,data: data
,dataType: 'json'
,headers: options.headers || {}
,success: function(res){
//如果有数据解析的回调,则获得其返回的数据
if(typeof options.parseData === 'function'){
res = options.parseData(res) || res;
}
//检查数据格式是否符合规范
if(res[response.statusName] != response.statusCode){
that.renderForm();
that.errorView(
res[response.msgName] ||
('返回的数据不符合规范,正确的成功状态码应为:"'+ response.statusName +'": '+ response.statusCode)
);
} else {
that.renderData(res, curr, res[response.countName]), sort();
options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时(接口请求+视图渲染)
}
that.setColsWidth();
typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
}
,error: function(e, msg){
that.errorView('请求异常,错误提示:'+ msg);
that.renderForm();
that.setColsWidth();
typeof options.error === 'function' && options.error(e, msg);
}
});
} else if(options.data && options.data.constructor === Array){ //已知数据
var res = {}
,startLimit = curr*options.limit - options.limit
res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
res[response.countName] = options.data.length;
//记录合计行数据
if(typeof options.totalRow === 'object'){
res[response.totalRowName] = $.extend({}, options.totalRow);
}
that.renderData(res, curr, res[response.countName]), sort();
that.setColsWidth();
typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
}
};
//遍历表头
Class.prototype.eachCols = function(callback){
var that = this;
table.eachCols(null, callback, that.config.cols);
return that;
};
//数据渲染
Class.prototype.renderData = function(res, curr, count, sort){
var that = this
,options = that.config
,data = res[options.response.dataName] || [] //列表数据
,totalRowData = res[options.response.totalRowName] //合计行数据
,trs = []
,trs_fixed = []
,trs_fixed_r = []
//渲染视图
,render = function(){ //后续性能提升的重点
var thisCheckedRowIndex;
if(!sort && that.sortKey){
return that.sort(that.sortKey.field, that.sortKey.sort, true);
}
layui.each(data, function(i1, item1){
var tds = [], tds_fixed = [], tds_fixed_r = []
,numbers = i1 + options.limit*(curr - 1) + 1; //序号
//若数据项为空数组,则不往下执行(因为删除数据时,会将原有数据设置为 [])
if(layui._typeof(item1) === 'array' && item1.length === 0) return;
//记录下标索引,用于恢复排序
if(!sort){
item1[table.config.indexName] = i1;
}
//遍历表头
that.eachCols(function(i3, item3){
var field = item3.field || i3
,key = options.index + '-' + item3.key
,content = item1[field];
if(content === undefined || content === null) content = '';
if(item3.colGroup) return;
//td内容
var td = ['<td data-field="'+ field +'" data-key="'+ key +'" '+ function(){ //追加各种属性
var attr = [];
if(item3.edit) attr.push('data-edit="'+ item3.edit +'"'); //是否允许单元格编辑
if(item3.align) attr.push('align="'+ item3.align +'"'); //对齐方式
if(item3.templet) attr.push('data-content="'+ content +'"'); //自定义模板
if(item3.toolbar) attr.push('data-off="true"'); //行工具列关闭单元格事件
if(item3.event) attr.push('lay-event="'+ item3.event +'"'); //自定义事件
if(item3.style) attr.push('style="'+ item3.style +'"'); //自定义样式
if(item3.minWidth) attr.push('data-minwidth="'+ item3.minWidth +'"'); //单元格最小宽度
return attr.join(' ');
}() +' class="'+ function(){ //追加样式
var classNames = [];
if(item3.hide) classNames.push(HIDE); //插入隐藏列样式
if(!item3.field) classNames.push('layui-table-col-special'); //插入特殊列样式
return classNames.join(' ');
}() +'">'
,'<div class="layui-table-cell laytable-cell-'+ function(){ //返回对应的CSS类标识
return item3.type === 'normal' ? key
: (key + ' laytable-cell-' + item3.type);
}() +'">' + function(){
var tplData = $.extend(true, {
LAY_INDEX: numbers
}, item1)
,checkName = table.config.checkName;
//渲染不同风格的列
switch(item3.type){
case 'checkbox':
return '<input type="checkbox" name="layTableCheckbox" lay-skin="primary" '+ function(){
//如果是全选
if(item3[checkName]){
item1[checkName] = item3[checkName];
return item3[checkName] ? 'checked' : '';
}
return tplData[checkName] ? 'checked' : '';
}() +'>';
break;
case 'radio':
if(tplData[checkName]){
thisCheckedRowIndex = i1;
}
return '<input type="radio" name="layTableRadio_'+ options.index +'" '
+ (tplData[checkName] ? 'checked' : '') +' lay-type="layTableRadio">';
break;
case 'numbers':
return numbers;
break;
};
//解析工具列模板
if(item3.toolbar){
return laytpl($(item3.toolbar).html()||'').render(tplData);
}
return parseTempData(item3, content, tplData);
}()
,'</div></td>'].join('');
tds.push(td);
if(item3.fixed && item3.fixed !== 'right') tds_fixed.push(td);
if(item3.fixed === 'right') tds_fixed_r.push(td);
});
trs.push('<tr data-index="'+ i1 +'">'+ tds.join('') + '</tr>');
trs_fixed.push('<tr data-index="'+ i1 +'">'+ tds_fixed.join('') + '</tr>');
trs_fixed_r.push('<tr data-index="'+ i1 +'">'+ tds_fixed_r.join('') + '</tr>');
});
that.layBody.scrollTop(0);
that.layMain.find('.'+ NONE).remove();
that.layMain.find('tbody').html(trs.join(''));
that.layFixLeft.find('tbody').html(trs_fixed.join(''));
that.layFixRight.find('tbody').html(trs_fixed_r.join(''));
that.renderForm();
typeof thisCheckedRowIndex === 'number' && that.setThisRowChecked(thisCheckedRowIndex);
that.syncCheckAll();
//滚动条补丁
that.haveInit ? that.scrollPatch() : setTimeout(function(){
that.scrollPatch();
}, 50);
that.haveInit = true;
layer.close(that.tipsIndex);
//同步表头父列的相关值
options.HAS_SET_COLS_PATCH || that.setColsPatch();
options.HAS_SET_COLS_PATCH = true;
};
table.cache[that.key] = data; //记录数据
//显示隐藏分页栏
that.layPage[(count == 0 || (data.length === 0 && curr == 1)) ? 'addClass' : 'removeClass'](HIDE);
//如果无数据
if(data.length === 0){
that.renderForm();
return that.errorView(options.text.none);
} else {
that.layFixed.removeClass(HIDE);
}
//如果执行初始排序
if(sort){
return render();
}
//正常初始化数据渲染
render(); //渲染数据
that.renderTotal(data, totalRowData); //数据合计
//同步分页状态
if(options.page){
options.page = $.extend({
elem: 'layui-table-page' + options.index
,count: count
,limit: options.limit
,limits: options.limits || [10,20,30,40,50,60,70,80,90]
,groups: 3
,layout: ['prev', 'page', 'next', 'skip', 'count', 'limit']
,prev: '<i class="layui-icon"></i>'
,next: '<i class="layui-icon"></i>'
,jump: function(obj, first){
if(!first){
//分页本身并非需要做以下更新,下面参数的同步,主要是因为其它处理统一用到了它们
//而并非用的是 options.page 中的参数(以确保分页未开启的情况仍能正常使用)
that.page = obj.curr; //更新页码
options.limit = obj.limit; //更新每页条数
that.pullData(obj.curr);
}
}
}, options.page);
options.page.count = count; //更新总条数
laypage.render(options.page);
}
};
//数据合计行
Class.prototype.renderTotal = function(data, totalRowData){
var that = this
,options = that.config
,totalNums = {};
if(!options.totalRow) return;
layui.each(data, function(i1, item1){
//若数据项为空数组,则不往下执行(因为删除数据时,会将原有数据设置为 [])
if(layui._typeof(item1) === 'array' && item1.length === 0) return;
that.eachCols(function(i3, item3){
var field = item3.field || i3
,content = item1[field];
if(item3.totalRow){
totalNums[field] = (totalNums[field] || 0) + (parseFloat(content) || 0);
}
});
});
that.dataTotal = {};
var tds = [];
that.eachCols(function(i3, item3){
var field = item3.field || i3;
//td 内容
var content = function(){
var text = item3.totalRowText || ''
,thisTotalNum = parseFloat(totalNums[field]).toFixed(2)
,tplData = {}
,getContent;
tplData[field] = thisTotalNum;
//获取自动计算的合并内容
getContent = item3.totalRow ? (parseTempData(item3, thisTotalNum, tplData) || text) : text;
//如果直接传入了合计行数据,则不输出自动计算的结果
return totalRowData ? (totalRowData[item3.field] || getContent) : getContent;
}()
,td = ['<td data-field="'+ field +'" data-key="'+ options.index + '-'+ item3.key +'" '+ function(){
var attr = [];
if(item3.align) attr.push('align="'+ item3.align +'"'); //对齐方式
if(item3.style) attr.push('style="'+ item3.style +'"'); //自定义样式
if(item3.minWidth) attr.push('data-minwidth="'+ item3.minWidth +'"'); //单元格最小宽度
return attr.join(' ');
}() +' class="'+ function(){ //追加样式
var classNames = [];
if(item3.hide) classNames.push(HIDE); //插入隐藏列样式
if(!item3.field) classNames.push('layui-table-col-special'); //插入特殊列样式
return classNames.join(' ');
}() +'">'
,'<div class="layui-table-cell laytable-cell-'+ function(){ //返回对应的CSS类标识
var str = (options.index + '-' + item3.key);
return item3.type === 'normal' ? str