首页 > 解决方案 > 数据表 - 将 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的链接,以了解我正在使用的示例:

标签: cssdatatables

解决方案


你的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>


推荐阅读