javascript - 如何删除 JQuery 数据表中的列?

标签 javascript jquery datatable datatables datatables-1.10

我想删除总计 = 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 的列。

提前谢谢您。

最佳答案

我建议您使用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/

关于javascript - 如何删除 JQuery 数据表中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314190/

相关文章:

javascript - 为什么 TypeScript 在可选链接运算符后显示 "Cannot invoke an object which is possibly ' undefined'.ts(2722)"错误?

asp.net - JavaScript拼图: window. confirm = divConfirm(strMessage)

jquery - 粘贴时如何使导航栏居中?

javascript - Codeigniter - jQuery 数据表 搜索和分页时不会保留复选框中的选中值

javascript - 使滚动上的 <path> 变为虚线

javascript - 在请求中放置单独的方向 API key

javascript - 使用 Reactjs 和 D3 创建气泡图

jQuery 显示隐藏 DIV

javascript - 在数据表日期列中显示月份名称和年份

javascript - jQuery 数据表 : Delete row and reload