选中复选框时,在dataTables中显示隐藏的列

时间:2017-08-14 08:03:26

标签: jquery datatables show-hide

我试图显示隐藏在dataTable中的列。我从dataTables文档中了解了我的代码,但它没有用。

var $dtable = $('#example');
              var dtable  = $dtable.DataTable({
                  "scrollX": true,
                  "info":     false,
                  "dom": 'Bfrtip',
                  "columns": [
                        {"data": "name", className: 'profile', visible: true},
                        {"data": "position", className: 'sensitive', visible: false},
                        {"data": "office", className: 'profile', visible: true},
                        {"data": "age", className: 'sensitive', visible: false},
                        {"data": "startdate", className: 'profile', visible: true},
                        {"data": "salary", className: 'sensitive', visible: false}
                  ],
                  "buttons": [
                        'csv'
                  ]
              });

              $('.rect-check input').change(function(e){
                  console.log($(this).data('column'))

                  // Get the column API object
                  var column = $dtable.DataTable().column($(this).data('column'));

                  // Toggle the visibility
                  column.visible(true);
              })

HTML

<div class="rect-check">
  <input data-column="sensitive" type="checkbox"> Show sensitive
</div>

<table width="100%" class="display" id="example" cellspacing="0">
....

检查codepen

上的完整示例

1 个答案:

答案 0 :(得分:0)

由于您正在引用某个类,因此必须按原样处理它:

<input data-column=".sensitive" type="checkbox"> Show sensitive
                    ^ or add a dot when you retrieve it. 

然后它有效。使用列来获取多个列而不仅仅是第一个匹配,并迭代结果:

$('.rect-check input').change(function(e){
  // Get the column API object
  var className = $(this).data('column');
  var columns = dtable.columns(className);
  // Toggle the visibility
  columns.each(function() {
    this.visible(true)
  })  
})

将您的codepen移动到小提琴 - &gt;的 http://jsfiddle.net/s8005xg1/