如何使用datatable.net服务器端处理条件显示/隐藏列



我正在使用DataTable 1.10来生成表。我使用服务器端处理。根据另一个变量(状态),我想在表中显示或隐藏一个额外的列。如何使用datatable.net服务器端处理条件显示/隐藏列?这是我的代码(简化):

 $('#' + id).DataTable({
            dom: "< <'col-md-4 col-sm-12 col-xs-12'f><'col-md-8 col-sm-12 col-xs-12'l><'col-md-12 col-sm-12 col-xs-12 no-padding't><'col-md-3 col-sm-12 col-xs-12'i><'col-md-9 col-sm-12 col-xs-12'p>>"
        , responsive: true
        , createdRow: function (row, data, dataIndex) { //this is used to add data- attribute to td element
            $(row).find('td:eq(4)').attr('data-priority', data.Actions[0].action_priority);
        }
        , autoWidth: true //false
        , scrollX: true
        , pageResize: true
        , serverSide: true
        , processing: true
        , pageLength: 100
        , deferRender: true
        , ajax: {
            url: actionURL,
            type: 'POST',
            contentType: "application/json",
            data: function (model) {
                model.statusID = statusID ;
            },
        }
        , columnDefs:
          [
            {
                targets: 0,
                createdCell: function (td, data, rowData, row, col) { 
*//this is the part that does not work
                   if (incidentStatusID == 1) {
                      //here show column
                      visible:true;
                   }
                  else{
                       //hide column...
                        visible: false;
                   }
                }
            },*
            {
                targets: 3,
                createdCell: function (td, data, rowData, row, col) { //this is used to add data- attribute to td element
                    $(td).attr('data-priority', data.Actions[0].action_priority);
                }
            }
          ]

也许我可以使用相当于 createdRow的 CC_1,而列?虽然我找不到一个。我该怎么做?

我找到了解决方案。它并不完美,因为它首先生成列并将其隐藏。

这是我要隐藏的列。我添加了一个ID。

<th id="controls" data-priority="-1">Controls</th>

然后,在数据表代码中,我向fnRowCallback添加了一个调用,以便在生成表之后隐藏或显示列(可能可以改进此列,因此仅在需要时生成列...)。然后,我检查了条件(变量" statusId")以显示或隐藏列,并用jQuery隐藏。

这是相关的新代码:

fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull)
{        
      if (statusID== 0) {
          $('#controls').hide();
          $('td:eq(-1)', nRow).hide();
      }
      else {
          $('#controls').show();
      }
}

最新更新