【问题标题】:How to remove columns in JQuery Datatables?如何删除 JQuery 数据表中的列?
【发布时间】:2015-09-27 15:12:57
【问题描述】:

我想删除总计 = 0 的列。

所以我尝试了不同的方式。

首先,我为所有列分配了 ID,例如;每个<td> 的列都会有它们的ID,例如:第一列<td ID = 'col_1'>,第二列全部<td ID = 'col_2'> 等。然后在页脚回调中,如果此列总数为零,则我尝试删除此$("col_"+i).remove() ;这段代码只删除了表头,所以我再次尝试使用 $("col_"+i).empty() 但它又是空的。仅限<th>

然后我尝试通过创建动态来隐藏列,但我没有得到任何值。

    "footerCallback": function ( row, data, start, end, display ) 
    {
        var api = this.api(), data;  
        var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ?    i : 0;};

        var col_gonna_invis = '[';
        for(i=1;i<length_of_coloumns;i++)
            {
                total_salary = api.column( i ).data().reduce( function (a, b) {return intVal(a) + intVal(b);},0 );
                $('#total_cont_'+i).html(total_salary); 
                if(total_salary == 0)
                {
                    col_gonna_invis += '{"targets": [ '+i+' ], "visible": false, "searchable": false },';
                }
            }
        col_gonna_invis += ']';alert(col_gonna_invis);  
    },

    "aoColumnDefs": col_gonna_invis;

请有人帮我解决这个问题,或者请有人告诉我如何隐藏或删除页脚总数为 0 的列。

提前谢谢你。

【问题讨论】:

  • 你能用小提琴复制你的问题吗?这样会更容易提供帮助。

标签: javascript jquery datatable datatables datatables-1.10


【解决方案1】:

我建议您使用visible() API 方法和sum() 插件:

使用 column().sum() 方法增强 API:

jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
    return this.flatten().reduce( function ( a, b ) {
        if ( typeof a === 'string' ) {
            a = a.replace(/[^\d.-]/g, '') * 1;
        }
        if ( typeof b === 'string' ) {
            b = b.replace(/[^\d.-]/g, '') * 1;
        }

        return a + b;
    }, 0 );
} );

现在,在 initComplete() 中,您可以非常轻松地隐藏 totalsum() 为 0 的列:

var table = $('#example').dataTable({
   //... 
   initComplete : function() {
      var api = this.api(), 
          colCount = api.row(0).data().length;
      for (var i=0; i<colCount; i++) {
          if (api.column(i).data().sum() == 0) {
              api.column(i).visible(false);
          }
      }     
    }
});

演示 -> http://jsfiddle.net/qer7e5os/

【讨论】:

  • @davidkonard 简直太棒了.. 非常感谢 :) 再次感谢您
猜你喜欢
  • 2013-07-04
  • 2021-09-29
  • 2018-12-30
  • 2023-01-12
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多