如何隐藏或显示使用 javascript 中的数据 table 创建的 table 的列?

How to hide or show column of table created using datatables in javascript?

当数据表的来源是 javascript 时,你知道如何隐藏或显示列吗?

显示或隐藏列的方法

 table = $('#example').DataTable();
var col = table.column("0").visible(false);

当数据源直接进入 html 时工作

<table id="example" class="row-border hover">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
...          

但是当 DataTable 有 javascript 源

时它不起作用并启动错误
 var table = $('#example').dataTable({
                   "data": source,
                    "columns": columns,
                    "columnDefs": defs
    });


 var col = table.column("0").visible(false);//ERROR!

请问您知道如何隐藏带有 javascript 源的数据表列吗?

尝试这样的事情,

var table = $('#example').dataTable({
  "data": source,
  "columns": columns,
  "columnDefs": [
  {
    "targets": [ 0 ],
    "visible": false,
  },
  "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull )     
  {
    $('td:eq(0)', nRow).hide();
  }
});

已更新。尝试添加 fnRowCallback。谢谢!

我终于找到了另一个答案:它不依赖于 html 或 json 来源,但新版本的 DataTable() 和旧版本的 dataTable() 之间存在差异

column(n).visible(bool) 

适用于 DataTable()

fnRowCallback 

适用于 dataTable()