1. 显示效果:
2. layui本身自带斑马线效果
在table.render({}),里面添加even属性即可。但这并不满足我这边的需求。
我的需求:字段【项目】值相同的,行的背景颜色相同,相邻的字段【项目】值不同的,背景颜色不同。
3.代码
// 渲染完成后执行的操作
var lastValue = null;
var colorIndex = 0; // 定义两种颜色切换使用的索引
// 遍历表格体所有行
$('.layui-table-body tr[data-index]').each(function (index, item) {
var $item = $(item);
var fieldValue = $item.find('td[data-field="ProjCode"]').text(); // 获取当前行字段值
// 判断字段值是否与上一行相同
if (lastValue === fieldValue) {
// 相同则应用相同的背景色
//$item.css('background-color', ['#f5f5f5', '#ffffff'][colorIndex]); // 这里是两种预设的背景色
$item.css('background-color', ['blue', 'red'][colorIndex]); // 这里是两种预设的背景色
} else {
// 不同则切换背景色
colorIndex = 1 - colorIndex; // 切换颜色索引
$item.css('background-color', ['blue', 'red'][colorIndex]);
}
lastValue = fieldValue; // 更新为当前行字段值
});