简体   繁体   English

jQuery Datatable 动态显示/隐藏列

[英]jQuery Datatable Show / hide columns dynamically

I am trying to show/hide datatable columns dynamically.我正在尝试动态显示/隐藏数据表列。 For this, here I am going with the example which is given by the official datatable website.为此,我将使用官方数据表网站给出的示例

This is the code for my datatable:这是我的数据表的代码:

HTML: HTML:

<table id="itemEdit" class="table collapsed">
    <thead>
      <tr>
        <th>ID</th>
        <th>SKU</th>
        <th>Barcode</th>
        <th>Item Name</th>
        <th>Price</th>
      </tr>
    </thead>

    <tbody></tbody>
</table>

JS: JS:

var tableId = "#itemEdit";
var $_table = $(tableId).DataTable({ 
    //dom:            "Bfrtip",
    scrollY:        "300px",
    scrollX:        true,
    scrollCollapse: true,

    "ajax": './view_items.php',
    "columns": [            
      {"data": "id", "class": "align-middle"},
      {"data": "sku","class": "align-middle"},            
      {"data": "barcode","class": "align-middle"},            
      {"data": "itemname","class": "align-middle"},            
      {"data": "price","class": "align-middle"},            
    ]
})

HTML for <a> : <a>的 HTML:

<div class="btn-group dropright dd-backdrop">
    <button type="button" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="sr-only">Columns</span>
    </button>
    <div class="dropdown-menu p-0 ">
      <a href="#" class="dropdown-item toggle-vis" data-column="4">
        Item Name
      </a>
    </div>
</div> 

My question is, just I want to add CSS class for the a.toggle-vis base on its visibility.我的问题是,我只是想根据a.toggle-vis的可见性为它添加CSS类。

I tried it something like this.我试过这样的东西。 But its not working for me.但它不适合我。

$('a.toggle-vis').on('click', function (e) {
    e.preventDefault();

    // Get the column API object
    var column = $_table.column($(this).attr('data-column'));

    //console.log(column)

    if (column.visible() === true) {
      $(this).addClass('showing').removeClass('not-showing');
      column.visible(!column.visible());
    } else {
      $(this).removeClass('showing').addClass('not-showing');
      $(this).removeClass('active');
    }
       
    $_table.columns.adjust().draw( false ); // adjust column sizing and redraw
});

Hope somebody may help me out.希望有人可以帮助我。

In the end, your approach is correct - with one small change: Move the following line (which toggles the column's visibility)...最后,您的方法是正确的 - 只需稍作改动:移动以下行(切换列的可见性)...

column.visible(!column.visible());

...from inside the if statement to before the if statement. ...从if语句内部到if语句之前。

That will ensure the toggle always happens for the selected column.这将确保切换总是发生在选定的列上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM