Datatables动态表头,动态列渲染,可用

Datatables动态表头,动态列渲染,可用_第1张图片我理解的动态列就是在dt初始化的时候不确定列的多少,即columns里的内容是根据实际操作变化而变化,在这个前提下,我做了一个简单的实例,希望帮助到大家,看下面代码:

<div class="container">
    
    <table id="example" class="table table-striped table-bordered">
    table>
div>
 
  
 var table;
    var colunmsStr = "name,position,salary,start_date,office,extn";
    var columsName = {
        "name": "姓名",
        "position": "位置",
        "salary": "薪水",
        "start_date": "开始时间",
        "office": "办公",
        "extn": "其他"
    };
    $(function () {
        getAllColumnsName();

        $("#rebulidTable").click(function () {
            var columnArr = $("input[name='allColumns']:checked");
            var columnStrIn = "";

            var columnsArray = [];

            //动态组装列
            $(columnArr).each(function (i, o) {
                var json = {data: null, title: null};
                o = $(o);
                columnStrIn += o.val();
                if (i != columnArr.length - 1) {
                    columnStrIn += ",";
                }
                json.data = o.val();
                json.title = columsName[o.val()];
                columnsArray.push(json);
            });
            colunmsStr = columnStrIn;

            //改变列的结构,先销毁前面的实例
            table.destroy();
            // 列改变了,需要清空table
            $("#example").empty();
            table = createTable(columnsArray);
        });



        //第一次初始化,加载所有列
        var columns = [
            {"data": "name", "title": columsName["name"]},
            {"data": "position", "title": columsName["position"]},
            {"data": "salary", "title": columsName["salary"]},
            {"data": "start_date", "title": columsName["start_date"]},
            {"data": "office", "title": columsName["office"]},
            {"data": "extn", "title": columsName["extn"]}
        ];
        table = createTable(columns);
    });

    //公共方法,多次初始化调用
    function createTable(columns) {
        return $("#example").DataTable({
            ajax: {
                url: "/dynamicColumns.jsp",
                data: {
                    "cols": colunmsStr
                }
            },
            //因为需要多次初始化,所以需要设置允许销毁实例
            "destroy": true,
            //列的配置信息通过变量传进来
            "columns": columns,
            "language": {
                "lengthMenu": "每页_MENU_ 条记录",
                "zeroRecords": "没有找到记录",
                "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
                "infoEmpty": "无记录",
                "search": "搜索:",
                "infoFiltered": "(从 _MAX_ 条记录过滤)",
                "paginate": {
                    "previous": "上一页",
                    "next": "下一页"
                }
            }
        });
    }

你可能感兴趣的:(web前端)