【问题标题】:How do i color each cell based on condition in Datatables.js after rendering the table from json data? [duplicate]从 json 数据渲染表格后,如何根据 Datatables.js 中的条件为每个单元格着色? [复制]
【发布时间】:2019-05-14 10:07:23
【问题描述】:
var dataset = [];
var columns = sfdata.columns

sfdata.data.forEach(function (item,index) {
    var n2 = item.items
    dataset.push(n2)
});

$(document).ready(function() {
    $('#example').DataTable({
        data: dataset,
        columns: [
            { title: "index" },
            { title: "Name" }

        ]
    });
});

所以我在 spotfire 中创建了默认表,现在的问题是我如何根据条件(如果数据 [2] > 10 则背景颜色为“红色”)为列中的值着色。我实例化它错了吗?如何让它工作?

【问题讨论】:

  • 您可以通过编辑您的问题来使用示例数据创建 sn-p 吗?
  • 在列定义中,您可以添加class 属性,也可以使用rowDrawCallback 来实现同样的效果

标签: javascript jquery datatables spotfire datatables-1.10


【解决方案1】:

您是否尝试将createdRow 添加到DataTable() 调用中?

$("#example").DataTable({
  "data": dataset,
  "columns": [
    { "title": "index" },
    { "title": "Name" }
  ],
  "createdRow": (row, data, dataIndex) => {
    if(data[2] >  10)
    {
      $(row).addClass("redClass");
    }
  }
});

在 CSS 中:

.redClass
{
  background-color: red;
}

这直接来自DataTables documentation

【讨论】:

    【解决方案2】:

    如果您想根据列设置特定单元格的样式,您必须使用带有渲染选项的 columnDefs 作为回调,目标是指您想要控制单元格的列(您也可以查看here )。

    所以代码应该是这样的:

      var dataSet = [
    ["Tiger Nixon", 1, "Edinburgh", "5421", "2011/04/25", "$320,800"],
    ["Garrett Winters", 12, "Tokyo", "8422", "2011/07/25", "$170,750"],
    ["Ashton Cox", 4, "San Francisco", "1562", "2009/01/12", "$86,000"],
    ["Cedric Kelly", 5, "Edinburgh", "6224", "2012/03/29", "$433,060"],
    ["Airi Satou", 23, "Tokyo", "5407", "2008/11/28", "$162,700"],
    ["Brielle Williamson", 54, "New York", "4804", "2012/12/02", "$372,000"],
    ["Herrod Chandler", 2, "San Francisco", "9608", "2012/08/06", "$137,500"]
      ];
    
    var columnDefs = [{
       title: "Name"
      }, {
        title: "Position"
      }, {
        title: "Office"
      }, {
        title: "Extn."
      }, {
        title: "Start date"
      }, {
        title: "Salary"
      }];
    
    var myTable;
    
    myTable = $('#example').DataTable({
       data: dataSet,
       columns: columnDefs,
       columnDefs: [{
         targets: 1, // this means controlling cells in column 1
         render: function(data, type, row, meta) { 
           if (data > 10) { // here is your condition
             return '<div class="red-color">' + data + '</div>';
           } else {
             return data;
           }
         }
       }]
     });
    

    这是一个有效的snippet

    【讨论】:

    • 如何给多列条件?
    • columnDefs 接受一个对象数组,你可以认为每个对象代表一列,你只需要改变目标数。我已经更新了sn-p 你可以看看here
    【解决方案3】:

    你可以使用columnDefs来实现你想要的。

    targets 是您要过滤掉的列号,render 是要在该列被渲染时触发的事件。所以,你有了你想要的数据,你可以根据数据过滤掉结果并应用background-color

    这里是演示。

    var dataSet = [{
      index: 1,
      name: "test"
    }, {
      index: 2,
      name: "test2"
    }, {
      index: 3,
      name: "test3"
    }];
    
    
    $(document).ready(function() {
      $('#example').DataTable({
        data: dataSet,
        columns: [{
            data: "index"
          },
          {
            data: "name"
          }
        ],
        columnDefs: [{
         targets : [0],
          render: function(data, type, row) {
          
            if(row.index>2){
              return "<div style='background-color:red'>"+data+"<div>";
            }
            return data;
          }
        }]
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet" />
    <table id="example" class="display" width="100%"></table>

    【讨论】:

      【解决方案4】:

      $(document).ready(function() {
         var table = $('#example').DataTable({
            'ajax': 'https://api.myjson.com/bins/qgcu',
           "columnDefs": [ {
              "targets":3,
              "render": function ( data, type, row, meta ) {
               var highlight="";
               if(data==5407 || data == 1314)highlight="link"; // Put your conditions here
                return '<span class="'+highlight+'"><i class="fa fa-heart" aria-hidden="true"></i> '+data+'</span>';
              }
        } ],
        "initComplete": function(settings, json) {
          $(".link").parent().addClass("link");
        }
         });  
        
      });
      .link{
        color:white;
        background-color:red;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script>
      <script src="https://cdn.rawgit.com/ashl1/datatables-rowsgroup/fbd569b8768155c7a9a62568e66a64115887d7d0/dataTables.rowsGroup.js"></script>
      <link href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css" rel="stylesheet"/>
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">
      <h3>jQuery DataTables - ROWSPAN in table body TBODY</h3>
      
      <hr><br>
          
      <table id="example" class="display" cellspacing="0" width="100%">
         <thead>
            <tr>
               <th>Name</th>
               <th>Position</th>
               <th>Office</th>
               <th>Extn.</th>
               <th>Start date</th>
               <th>Salary</th>
            </tr>
         </thead>
         <tfoot>
            <tr>
               <th>Name</th>
               <th>Position</th>
               <th>Office</th>
               <th>Extn.</th>
               <th>Start date</th>
               <th>Salary</th>
            </tr>
         </tfoot>
      </table>

      使用column.render 来实现这一点。希望这会有所帮助。

      【讨论】:

      • 谢谢。但我无法使用“Ajax”属性提取数据。
      • 改用数据集,我从远程位置获取数据。
      • 还有一件事,你知道如何在单元格中添加图标吗?我尝试使用 bootstrap css 但它不起作用,如果你有任何工作可以通过 CDN 传递给我吗?你是怎么做到的?
      • @ShricharanArumugam 使用字体真棒
      • @ShricharanArumugam 我用图标更新了答案,请检查
      猜你喜欢
      • 2014-05-04
      • 2023-04-07
      • 2019-11-12
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多