一、动态表格
关键点:
Object.keys(data.data[0]) 获取所需要的表头字段;- colss.push({ align: ‘center’, title: arr[0], colspan: 2 });push cols 所需要的格式到数组里,其中
field 使用步骤1所得到的; cols: [[]] 根据固定格式,传入参数cols: [colss, colsData] - 注意步骤3,对于colspan=1的设置,需要增加空白行
{ title: '', field: '', hide: true }; 不然会出现thead与tbody不对应;
二、单元格条件渲染
done 时渲染
- 定位单元格,
lay-id 是对应table.render()中的id; - 动态声明变量
let attrName = 'role' + i;vars[attrName] = $(tr[i]).text().split('%'); $().css() 进行渲染,多个值使用{'Cname':'value','Cname':'value'}
三、效果图
$('.layui-table-view[lay-id="dcTableFuc2"]').children('.layui-table-box').children('.layui-table-body').find('table tbody tr[data-index="0"] td')
function dcTableFuc2() {
$.ajax({
url: '',
type: "",
data: {},
dataType: "json",
success: function (data) {
var colss = [];
var colsData = [];
var keys = Object.keys(data.data[0])
var lineOne = data.header[0];
var dataList = data.data[0];
var dataArr = [];
var arr = [];
for (var i in lineOne) {
arr.push(lineOne[i]);
}
colss.push({ align: 'center', title: arr[0], colspan: 2 });
for (let i = 1; i < arr.length; i++) {
colss.push({ align: 'center', title: arr[i], colspan: 2 });
}
for (var i in dataList) {
dataArr.push(dataList[i]);
}
colsData.push({ title: '', field: '', hide: true });
for (let i = 0; i < dataArr.length; i++) {
colsData.push({ field: keys[i], align: 'center', title: dataArr[i], colspan: 1 });
}
table.render({
elem: '#'
, method: ""
, dataType: "json"
, id: ''
, url: ''
, page: false
, where: {}
, cols: [colss, colsData]
, parseData: function (res) {
res.data.shift();
return {
"code": res.code,
"msg": res.msg,
"count": res.count,
"data": res.data
}
},
done: function (res, curr, count) {
var len = res.data.length - 1;
res.data.pop();
res.data.forEach(function (item, index) {
var tr = $('.layui-table-view[lay-id="dcTableFuc2"]').children('.layui-table-box').children('.layui-table-body').find('table tbody tr[data-index="' + index + '"] td');
var trTotal = $('.layui-table-view[lay-id="dcTableFuc2"]').children('.layui-table-box').children('.layui-table-body').find('table tbody tr[data-index="' + len + '"]');
trTotal.css('background-color', '#cccccc');
let vars = [];
let varsText = [];
for (var i = 3; i < tr.length; i = i + 2) {
let attrName = 'role' + i;
vars[attrName] = $(tr[i]).text().split('%');
let attrNameText = 'text' + i;
varsText[attrNameText] = Number(vars[attrName][0])
if (varsText[attrNameText] != NaN && varsText[attrNameText] >= 100) {
$(tr[i]).css({ 'background-color': '#00b050', 'color': 'white' });
} else if (varsText[attrNameText] != NaN && varsText[attrNameText] < 100) {
$(tr[i]).css({ 'background-color': '#e6b8b7', 'color': 'white' });
}
}
});
}
});
},
error: function () {}
});
};
|