1 回答

TA贡献1829条经验 获得超7个赞
我知道执行此操作的最简单方法是使用该columnDefs.render选项以及一些支持 CSS。
这是 CSS,在我的例子中,我将其包含在<head>HTML 页面的部分中:
<style>
.bg_red {
background-color: red !important;
}
.bg_yellow {
background-color: yellow !important;
}
.bg_green {
background-color: green !important;
}
</style>
!important请注意CSS 中的使用。这有点粗糙,但意味着此 CSS 会覆盖 DataTables 可能应用的任何行阴影(例如所谓的“斑马条纹”)。
我的测试表只是以下硬编码的 HTML:
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr><th>A</th><th>B</th><th>C</th></tr>
<thead>
<tbody>
<tr><td>R</td><td>R</td><td>Y</td></tr>
<tr><td>Q</td><td>X</td><td>G</td></tr>
</tbody>
</table>
DataTables函数如下:
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
columnDefs: [ {
targets: [1, 2],
"render": function ( data, type, row, meta ) {
var table = $('#example').dataTable().api();
if (type === 'display') {
var node = table.cell(meta.row, meta.col).nodes().to$();
if ( data === 'R' ) {
node.addClass('bg_red');
} else if ( data === 'G' ) {
node.addClass('bg_green');
} else if ( data === 'Y' ) {
node.addClass('bg_yellow');
}
}
return data;
}
} ]
} );
} );
</script>
该targets: [1, 2]选项意味着渲染逻辑将仅适用于我的表中的第二列和第三列(第一列的索引为零)。
该type === 'display'选项意味着我们只检查每个单元格的显示值。这可能与过滤器和排序值不同。在我的简单情况下,没有区别,但明确处理这个问题是个好主意。
渲染逻辑将相关的类名添加到表的<td>标签中 - 这是 DOM 的一部分,而不是 DataTables 本身的一部分。这就是我们访问每个单元格node对象的原因。
使用此render功能还意味着即使您对表格进行排序和筛选,格式也会遵循数据。否则,在排序/过滤后,错误的单元格将突出显示。
添加回答
举报