css - 数据表 - 将 css 添加到特定单元格
问题描述
我正在使用 Datatables 填充和显示我的数据。Revenue Growth
如果满足特定条件,我正在尝试将 css 添加到我的列下特定单元格的背景中。
例如:如果收入增长列小于 3,那么我想制作那个单元格background-color: red
这是我用来填充我的表的数组:
const data = [
{title: "Walk in", totalRevenue: 2002, growth: 3.2},
{title: "Retail", totalRevenue: 1231, growth: 2.2},
{title: "Hospital", totalRevenue: 5421, growth: 1.9},
{title: "Online", totalRevenue: 2442, growth: 3.2},
{title: "Fitness", totalRevenue: 8742, growth: 0.3}
]
我已经尝试过使用
rowCallback: function(row, data, index){
if(data[2] < 3){
$(row).find('td:eq(2)').css('background-color', 'red');
}
我相信这是检查第 3 列,这将是growth
我的数组中的值。目前使用这行代码,我的数据表没有改变。
我的预期结果是让任何小于 3 的值的背景显示为红色。
这是一个指向jsfiddle的链接,以了解我正在使用的示例:
解决方案
你的data
参数rowCallback
是一个对象。
if (data.growth < 3) {
$(row).find('td:eq(2)').css('background-color', 'red');
}
只需要将 if 条件从更改data[2]
为data.growth
$(document).ready(function() {
let className = ""
const data = [{
title: "Walk in",
totalRevenue: 2002,
growth: 3.2
}, {
title: "Retail",
totalRevenue: 1231,
growth: 2.2
},
{
title: "Hospital",
totalRevenue: 5421,
growth: 1.9
},
{
title: "Online",
totalRevenue: 2442,
growth: 3.2
},
{
title: "Fitness",
totalRevenue: 8742,
growth: 0.3
}
]
var table = $('#example').DataTable({
rowCallback: function(row, data, index) {
console.log({
data
})
if (data.growth < 3) {
$(row).find('td:eq(2)').css('background-color', 'red');
}
},
"columnDefs": [{
"targets": [1, 2],
"className": 'dt-body-right'
}, ],
data: data,
responsive: true,
paging: true,
searching: false,
bInfo: true,
"order": [
[2, "desc"]
],
"pageLength": 20,
columns: [{
data: "title",
title: "Title",
},
{
data: "totalRevenue",
title: 'Revenue'
},
{
data: "growth",
title: 'Revenue Growth'
},
]
});
});
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" style="width:100%">
</table>
推荐阅读
- nullpointerexception - 在对象中具有“深度”访问权限的模式 (Java)
- python - 我是否必须使用指针来使用“curve_fit”Scipy 函数调用“popt”变量?
- google-colaboratory - Google Colab 标头未在目录中显示前置数字
- google-cloud-platform - GCP:如果没有项目访问权限,是否可以访问资源?
- json - VB 变量 JSON 字符串
- javascript - 开关盒内的Nodejs Promise给出错误
- python - 是否可以将 Spyder 配置为停止打开新窗口(窗格)
- kubernetes - Kubernetes pod 部署未更新
- python - 正则表达式在括号之间复制内容
- python - 如何在 keras 中编写自定义损失函数?