【问题标题】:jQuery datatable immediately hide columnjQuery数据表立即隐藏列
【发布时间】:2017-09-12 17:30:52
【问题描述】:

我让 jQuery 数据表隐藏列功能正常工作。以下代码将隐藏表格的第二列:

HTML

<a href="#" class="btn toggle-vis" data-column="1" id="hideColumn">Show/Hide</a>

JS

$(document).ready(function()
{
  var table = $('#example1').DataTable();

  $('a.toggle-vis').on('click', function(e)
  {
    e.preventDefault();
    var column = table.column($(this).attr('data-column'));
    column.visible( ! column.visible());
  });
}

我想做的是在用户第一次进入页面时隐藏该列。该列仅在单击时显示。

如何调整代码来达到这个效果?

【问题讨论】:

标签: javascript jquery datatable datatables


【解决方案1】:

你需要使用 columnDefs

试试:

var table = $('#example1').DataTable(
{
    "columnDefs": [
        {
            "targets": [ 2 ],
            "visible": false
        }
    ]
} );

编辑

我不确定为什么这不起作用。在此处添加代码,因为在评论中显示效果不佳。 试试这个:

var table = $('#example1').DataTable(); 
table.column(1).visible(false);

【讨论】:

  • 感谢您的回复。没有错误,同时也没有成功。
  • 这实际上是该列的从零开始的索引,因此第二列应该是 [1]。
  • 不知道为什么这不起作用,但你可以试试 `var table = $('#example1').DataTable(); table.column(1).visible(false);
【解决方案2】:

试试这个

$(function () {    
    // To hide the table header during page load
    $("#example1 tr th:nth-child(2)").hide();

    // To hide the 2nd column during page load    
    $("#example1 tr td:nth-child(2)").each(function () {
        $(this).hide();
    });


    // Hide and show while clicking the link
    $(".toggle-vis").click(function () {
        var col = $(this).data("column");

        // Hide/Show the header
        $("#example1 tr th:nth-child(" + col + ")").is(":visible") ? $("#example1 tr th:nth-child(" + col + ")").hide() : $("#example1 tr th:nth-child(" + col + ")").show();

        // Hide/Show the details
        $("#example1 tr td:nth-child(" + col + ")").each(function () {
            $(this).is(":visible") ? $(this).hide() : $(this).show();
        });
    });

});

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多