jQuery DataTables如何隐藏列而不将其从DOM中删除

26

我需要在jQuery Datatables中隐藏一列。当使用bVisible属性隐藏此列时,它会从DOM中消失。

我想将一列的单元格的display属性设置为none,以便值不出现在视图中,但它们仍然存在于DOM中。我正在隐藏的列唯一标识行,并且在选择行时需要知道唯一ID。如何实现这一点。

我正在使用服务器端分页的aaData属性来填充表格。

我查看了这个问题,但这些选项会将其从DOM中删除。 jquery datatables hide column

5个回答

49

您应该在columnDefscolumns中使用className

请在您的CSS中定义hide_column类,如下所示:

.hide_column {
    display : none;
}

您有两种方法分配 .hide_column 类:

使用 columnDefs(将自定义类分配给第一列):

$('#example').DataTable( {
  columnDefs: [
    { targets: [ 0 ],
      className: "hide_column"
    }
  ]
} );

$('#example').DataTable( {
  "columns": [
    { className: "hide_column" },
    null,
    null,
    null,
    null
  ]
} );

从此处获取的代码段


旧答案

尝试添加

"sClass": "hide_column"

这应该使该列隐藏...


1
这个答案是正确的,但重要的是要注意,在 CSS 中添加 hide_column 类别才能使其正常运行。作者在“旧的回答”部分底部放置的方式使人误以为它对当前答案不再需要。 - robbpriestley
2
使用sClass标签来处理列,效果非常好。谢谢。 - George Eivaz
@Siddharth,回答内容哪里老旧了?不管怎样,我只是替换了大写字母D。 - Daniel
你好!我有一个关于这个的问题。我看到了这个,我也在我的数据表中使用了它,但是我的问题是这样的。我的数据表中每行都有两个复选框,一个是状态,另一个是ID。我隐藏了ID列,以免看起来凌乱。目的是我可以更新我的数据表中的数据。我将我的数据表包装在一个<form>中,以便可以传递到服务器端。现在的情况是,当我隐藏并尝试更新第一页的1-10条数据时,它会更新并且没有错误。但是在更新第二页时,它不会读取隐藏的列。它会从服务器产生错误。@Daniel - user14716889
@ERROR401 我认为你最好打开一个新的问题,并提供所有必要的代码(最小样例)。 - Daniel
嗨@Daniel,这是我的问题链接,虽然我在互联网上找到了一些东西,但如果你有解决方案,提前感谢:))。https://stackoverflow.com/questions/66470718/datatable-using-columndefs-not-working-if-using-it-to-hide-specific-column-and-d - user14716889

11

在Daniel的回答基础上补充:

css:

th.hide_me, td.hide_me {display: none;}
在 datatables 的初始化中:
"aoColumnDefs": [ { "sClass": "hide_me", "aTargets": [ 0 ] } ] // first column in visible columns array gets class "hide_me"

记得将隐藏类添加到您的表头单元格中:

<thead>
    <th class="hide_me">First Column</th>
    <th>Second Column</th>
    <th>Third Column</th>
</thead>

如果您正在使用服务器端处理,并希望从ajax源传递数据而不让它在数据表中可见,那么这也是一个有用的策略。您仍然可以在前端检索到列的值,而无需显示它。这对于通过隐藏数据值进行过滤等操作非常有帮助。

示例:

// In datatables init file
<script>
    var filteredValues = [];
    $('td.your_filtering_class').each(function(){
        var someVariable = $(this).find('.hide_me').html();
        filteredValues.push(someVariable);
    }
</script>

5
如果您想要隐藏多个列:
$('#example').dataTable({
  "columnDefs": [{ 
    "targets": [0,1,3], //Comma separated values
    "visible": false,
    "searchable": false }
  ]
});

这是不正确的。他们明确指定不想使用 visible 属性。 - beechovsky

0

这是我为您做出的贡献。

不确定代码是否正确,但它可以工作。

如果您像我一样有多个设置列。

$('#example').dataTable( {
  "columnDefs": [ {
        "targets"  : 'no-sort',
        "orderable": false,
        "order": [],
    }],
    "columnDefs": [ {
        "targets"  : 'hide_column',
        "orderable": false,
        "order": [],
        "visible": false
    }]
} );

-4
您可以使用方法hide
$(element).hide();

要显示元素,请使用方法show

$(element).show();

想要获取你想要的列,你可以使用 jQuery 的 n-th child 选择器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接