从数据表中获取列名

Jak*_*tre 2 jquery datatables datatables-1.10

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

我的主要问题是如何获取列名。我已经尝试过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
            });
Run Code Online (Sandbox Code Playgroud)

Die*_*goS 5

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

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

我已经针对https://datatables.net/示例表(其中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);
    });
Run Code Online (Sandbox Code Playgroud)

资料来源:

column.every()

column.visible()

问候!