从数据表中获取列名

Getting column names from DataTables

我正在以 html 形式动态生成 select。目的是能够将可见的数据表列换成不可见的数据表列。首先,我不确定如何完成实际的切换。

我的主要问题是如何获取列名。我试过 window.table.api().columns()[0];window.table.api().columns().data()[0];(我知道 [0] 索引是如何工作的,[0] 是我表示我要迭代的方式。有谁知道如何获取这些列的名称?

这是我的构造函数的示例:

   window.table =
            $table.dataTable({
                'ajax': {
                    'url': '/api/v1/data',
                    "type": "GET"
                },
                /**
                 * Specify which columns we're going to show
                 */
                columns:             {
                  data: 'Visible',
                  name: 'Visible',
                  visible: true
                  },
                    {
                    data: 'dataName',
                    name: 'Invisible',
                     visible: false
                },
                /**
                 * we want to disable showing page numbers, but still limit the number of results
                 */
                "dom": "t",
                /**
                 * let's disable some dynamic custom css
                 */
                asStripClasses: [],
                /**
                 * let's keep the pages reasonable to prevent scrolling
                 */
                pageLength: 8
            });

不是使用 Datatables API 查找这些名称,您可以使用 JQuery selectors 通过 DOM 获取列的名称,如下所示:

   //Replace yourTableId with the corresponding Id
    $("#yourTableId thead tr th").each(function(){
        alert(this.innerHTML); //This executes once per column showing your column names!
    }); 

我已经针对 https://datatables.net/ 样本 table(其中 yourTableId=example)对其进行了测试。

编辑:

因为 OP 说他想找到不可见的列并且这些列不能通过 DOM 直接访问,解决方案结果如下:

    //fill with the appropiate constructor
    var table = $('#yourTableId').DataTable();

    //iterate through every column in the table.
    table.columns().every( function () {        
            var visible = this.visible();
            if (!visible)
                alert(this.header().innerHTML);
    });

来源:

columns.every()

column.visible()

此致!