如何基于行ID(Index)修改gridjs表格行背景颜色?
解决Gridjs根据行字段设置背景色的问题
你当前的代码存在逻辑错误:在style.tr里用模板循环所有行,会生成多个重复的background-color属性,最终只有最后一个会生效,无法实现每行根据Index值动态设置背景色。以下是两种可行的解决方案:
方案一:使用rowClass绑定CSS类(推荐)
这种方式将样式逻辑与代码分离,更易维护,且支持分页、排序后的动态行样式。
- 先定义CSS样式:
/* Index <=1 的行背景色 */ .row-highlight { background-color: #e3bfcd; } /* Index >1 的行背景色 */ .row-muted { background-color: #d9dcde; }
- 修改Grid配置,添加
rowClass配置项:
const grid2 = new gridjs.Grid({ columns: [ { id: 'index', name: 'Index' }, { id: 'name', name: 'Name' }, ], data: [ {% for message4 in messages4 %} { index: '{{ message4['Index'] }}', name: '{{ message4['Name'] }}', }, {% endfor %} ], search: true, sort: true, pagination: true, resizable: true, // 根据行数据动态返回类名 rowClass: (row) => { // 将字符串类型的Index转为数字后判断 const index = parseInt(row.data.index); return index > 1 ? 'row-muted' : 'row-highlight'; } }).render(document.getElementById('grid_table_wikidata'));
方案二:直接通过style.tr函数设置行样式
如果不想额外写CSS,可以直接在style.tr中传入函数,动态返回样式对象:
const grid2 = new gridjs.Grid({ columns: [ { id: 'index', name: 'Index' }, { id: 'name', name: 'Name' }, ], data: [ {% for message4 in messages4 %} { index: '{{ message4['Index'] }}', name: '{{ message4['Name'] }}', }, {% endfor %} ], search: true, sort: true, pagination: true, resizable: true, style: { // 传入函数,参数为当前行数据 tr: (row) => { const index = parseInt(row.data.index); return { 'background-color': index > 1 ? '#d9dcde' : '#e3bfcd' }; } } }).render(document.getElementById('grid_table_wikidata'));
关键说明
- 由于模板渲染出的
index是字符串类型,需要用parseInt()转为数字后再做大小比较。 - Gridjs的
row.data对应你传入的每一条数据对象,所以可以直接通过row.data.index获取当前行的Index值。
内容的提问来源于stack exchange,提问作者user7665853
相关产品推荐
相关产品推荐

