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功能還意味著即使您對表格進行排序和篩選,格式也會遵循數據。否則,在排序/過濾后,錯誤的單元格將突出顯示。
添加回答
舉報