jquery - 从 DataTable 中获取列名

标签 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
            });

最佳答案

您可以使用 JQuery selectors 获取列的名称,而不是使用 Datatables API 查找这些名称。像这样通过 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/ 对其进行了测试示例表(其中 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()

问候!

关于jquery - 从 DataTable 中获取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156966/

相关文章:

javascript - 有没有一种简单的方法可以在 React.JS 中包含像 DataTables 这样的 jQuery UI 插件?

jquery - 如何仅对 JQUERY 数据表中的一列启用排序

jquery - DataTable响应式显示某些列

php - 数据表 - 服务器端处理 - 数据库列合并

javascript - 输入框日期选择器不适用于 jQuery DataTables 的所有页面

jquery - 滚动到数据表中的特定行

jquery - 使用jquery和modernizr插入html

jquery - jquery highcharts 中的背景颜色变化

jquery - 使用 svg 内的链接平滑滚动或缩放文本,我应该尝试什么?

javascript - 即使调整大小, Canvas 文本也始终居中吗?