隐藏列时,DataTable会重新加载到第一页

时间:2016-09-29 18:03:41

标签: javascript jquery datatable

我正在使用jquery dataTable插件,我试图允许用户隐藏列。

代码正在运行,但是当我转到不是第一页的页面时,我隐藏了一列,它会回到隐藏了列的第一页。

我希望它保留在用户所在的页面上并隐藏列。

    var oTable = $("#x").dataTable({
        responsive: true,
        "bFilter": true,
        "bPaginate": true,
        "order": [[5, 'desc']],
        "aoColumns": [
        {"bSortable": false },
        {"sClass": "text-center", "sWidth": "10%"},
        {"sClass": "text-center", "sWidth": "10%"},
        {"sClass": "text-center", "sWidth": "10%", "bSortable": false},
        {"sClass": "text-center", "sWidth": "10%", "bSortable": false},
        {"sClass": "text-center", "sWidth": "10%"}
        ]
    });
    $('.oculta-mostra').click(function(event) {
        event.preventDefault();
        $(this).children().first().toggleClass("label-success");
        $(this).children().first().toggleClass("label-danger");
        fnShowHide($(this).prop('id'));
    });
    function fnShowHide(iCol) {
        var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
        oTable.fnSetColumnVis( iCol, bVis ? false : true );
    }
    });

HTML

        <a href="" id="1" class="oculta-mostra" style="text-decoration: none">
          <span class="label label-success">J</span>
        </a>
        <a href="" id="2" class="oculta-mostra" style="text-decoration: none">
          <span class="label label-success">V</span>
        </a>
        <a href="" id="3" class="oculta-mostra" style="text-decoration: none">
          <span class="label label-success">E</span>
        </a>
        <a href="" id="4" class="oculta-mostra" style="text-decoration: none">
          <span class="label label-success">D</span>
        </a>
   <table id="x" class="table table-bordered table-striped table-hover" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>nome</th>
            <th>J</th>
            <th>V</th>
            <th>E</th>
            <th>D</th>
            <th>P</th>
        </tr>
    </thead>
    <tbody>
        @foreach( $x as $u )
        <tr>
            <td>{{ $u->nome }}</td>
            <td>{{ $u->peladas }}</td>
            <td>{{ $u->vitorias }}</td>
            <td>{{ $u->empates }}</td>
            <td>{{ $u->derrotas }}</td>
            <td>{{ $u->pontuacao }}</td>
        @endforeach
        </tr>
    </tbody>

1 个答案:

答案 0 :(得分:0)

显示和隐藏列的功能应该返回当前页面:

首先,获取当前页面的数量:

var iPage = Math.ceil(oTable.fnSettings()._iDisplayStart / oTable.fnSettings()._iDisplayLength )

其次,将页面设置为表格:

oTable.fnPageChange(iPage);

完整功能

function fnShowHide(iCol) {
    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    var iPage = Math.ceil(oTable.fnSettings()._iDisplayStart / oTable.fnSettings()._iDisplayLength )
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
    oTable.fnPageChange(iPage);
}

结果: http://jsfiddle.net/cmedina/7kfmyw6x/104/