bootstrap-table 表樹形展示案列

<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width,initial-scale=1.0" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <title>菜單管理</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-treegrid/0.2.0/css/jquery.treegrid.min.css">
</head>

<body>
<div class="container" style="border: 1px #ccc solid; width: 100%;">
    <h1>樹形表格 : Table Treegrid</h1>
    <table id="table"></table>
    <br/>
    <button οnclick="test()">選擇</button>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.0/extensions/treegrid/bootstrap-table-treegrid.js"></script>
<script src="https://cdn.bootcss.com/jquery-treegrid/0.2.0/js/jquery.treegrid.min.js"></script>
<script type="text/javascript">
    var $table = $('#table');
    var baseURL = "../../";
    var data = JSON.parse(
        '[{"menuId":1,"parentId":0,"status":1,"name":"用戶管理","permissionValue":"open:user:manage"},' +
        '{"menuId":2,"parentId":0,"status":1,"name":"系統管理","permissionValue":"open:system:manage"},' +
        '{"menuId":3,"parentId":1,"status":1,"name":"新增用戶","permissionValue":"open:user:add"},' +
        '{"menuId":4,"parentId":1,"status":1,"name":"修改用戶","permissionValue":"open:user:edit"},' +
        '{"menuId":5,"parentId":1,"status":0,"name":"刪除用戶","permissionValue":"open:user:del"},' +
        '{"menuId":6,"parentId":2,"status":1,"name":"系統配置管理","permissionValue":"open:systemconfig:manage"},' +
        '{"menuId":7,"parentId":6,"status":1,"name":"新增配置","permissionValue":"open:systemconfig:add"},' +
        '{"menuId":8,"parentId":6,"status":1,"name":"修改配置","permissionValue":"open:systemconfig:edit"},' +
        '{"menuId":9,"parentId":6,"status":0,"name":"刪除配置","permissionValue":"open:systemconfig:del"},' +
        '{"menuId":10,"parentId":2,"status":1,"name":"系統日誌管理","permissionValue":"open:log:manage"},' +
        '{"menuId":11,"parentId":10,"status":1,"name":"新增日誌","permissionValue":"open:log:add"},' +
        '{"menuId":12,"parentId":10,"status":1,"name":"修改日誌","permissionValue":"open:log:edit"},' +
        '{"menuId":13,"parentId":10,"status":0,"name":"刪除日誌","permissionValue":"open:log:del"}]');
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '菜單ID', field: 'menuId', visible: true, align: 'center', valign: 'middle', width: '80px'},
        {title: '菜單名稱', field: 'name', align: 'left', valign: 'middle', sortable: true, width: '260px'},
        {title: '上級菜單', field: 'parentName', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '圖標', field: 'icon', align: 'center', valign: 'middle', sortable: true, width: '80px', formatter: function(value, item, index){
            if(contains(item.icon,'/statics/')){
                return '<img src="'+baseURL+item.icon+'" style="width: 20px;" alt=""/>';
            }else if(contains(item.icon,'http://') || contains(item.icon,'https://')){
                return '<img src="'+item.icon+'" style="width: 20px;" alt=""/>';
            }else{
                return item.icon == null ? '' : '<i class="'+item.icon+' fa-lg"></i>';
            }
        }},
        {title: '類型', field: 'type', align: 'center', valign: 'middle', sortable: true, width: '100px', formatter: function(value, item, index){
            //console.log("value : "+JSON.stringify(value));    
            //console.log("item : "+JSON.stringify(item)); 
            //console.log("index : "+JSON.stringify(index)); 
            if(item.type === 0){
                return '<span class="label label-primary">目錄</span>';
            }
            if(item.type === 1){
                return '<span class="label label-success">菜單</span>';
            }
            if(item.type === 2){
                return '<span class="label label-warning">按鈕</span>';
            }
            if(item.type === 3){
                return '<span class="label label-info">系統</span>';
            }
        }},
        {title: '排序號', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: 'URL', field: 'url', align: 'center', valign: 'middle', sortable: true, width: '250px'},
        {title: '授權標識', field: 'perms', align: 'center', valign: 'middle', sortable: true}
        ]

    $(function() {
        //控制檯輸出一下數據
        //console.log(data);
        $table.bootstrapTable({
            data:data,
            //url: baseURL + "sys/menu/list",
            idField: 'menuId',
            dataType:'json',
            columns: [
                { field: 'check',  checkbox: true, formatter: function (value, row, index) {
                        if (row.check == true) {
                           // console.log(row.serverName);
                            //設置選中
                            return {  checked: true };
                        }
                    }
                },
                { field: 'name',  title: '名稱' },
               // {field: 'id', title: '編號', sortable: true, align: 'center'},
               // {field: 'pid', title: '所屬上級'},
                { field: 'status',  title: '狀態', sortable: true,  align: 'center', formatter: 'statusFormatter'  },
                { field: 'permissionValue', title: '權限值'  },
                { field: 'operate', title: '操作', align: 'center', events : operateEvents, formatter: 'operateFormatter' },
            ],
            // bootstrap-table-treegrid.js 插件配置 -- start
            //在哪一列展開樹形
            treeShowField: 'name',
            //指定父id列
            parentIdField: 'parentId',
            classes: "table table-bordered table-striped table-sm",
            pagination: false,//開啓分頁
            search: true, //開啓刷選
            cardView: false, //卡片模式
            onResetView: function(data) {
                //console.log('load');
                $table.treegrid({
                    initialState: 'collapsed',// 所有節點都摺疊
                    // initialState: 'expanded',// 所有節點都展開,默認展開
                    treeColumn: 1,
                    // expanderExpandedClass: 'glyphicon glyphicon-minus',  //圖標樣式
                    // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function() {
                        $table.bootstrapTable('resetWidth');
                    }
                });
                //只展開樹形的第一級節點
                // $table.treegrid('getRootNodes').treegrid('expand');
            },
            onCheck:function(row){
                //console.log('---~~^選中數據^~~---');
               // var datas = $table.bootstrapTable('getData');
                // 勾選子類
              //  selectChilds(datas,row,"menuId","parentId",true);
                // 勾選父類
              //  selectParentChecked(datas,row,"menuId","parentId")
                // 刷新數據
              //  $table.bootstrapTable('load', datas);
            },
            onUncheck:function(row){
            //    console.log('---~~^取消選中數據^~~---');
                var datas = $table.bootstrapTable('getData');
                selectChilds(datas,row,"menuId","parentId",false);
                $table.bootstrapTable('load', datas);
            },
            //加載數據時提示
            formatLoadingMessage:function() {
                return "數據加載中...";
            },
            //每頁顯示
            formatRecordsPerPage:function(pageNumber){
                return pageNumber+'行每頁';
            },
            //頁碼
            formatShowingRows:function(pageFrom, pageTo, totalRows){
                return "第"+pageFrom+"-"+pageTo+"行,總共"+totalRows+"";
            },
            formatSRPaginationPreText :function(){
                return '上一頁';
            },
            formatSRPaginationPageText:function(page){
                return '跳轉至'+page;
            },
            formatSRPaginationNextText:function(){
                return '下一頁';
            },
            formatDetailPagination:function(totalRows){
                return "總計:"+totalRows;
            },
            formatSearch:function(){
                   return  "搜索";
            },
            formatClearSearch:function(){
                return  "清除搜索";
            },
            formatNoMatches:function(){
                return  "未查詢到相關記錄";
            },
            formatPaginationSwitch:function(){
                return "隱藏顯示分頁";
            },
            formatPaginationSwitchDown:function(){
                return "顯示分頁";
            },
            formatPaginationSwitchUp:function(){
                return "隱藏分頁";
            },
            formatRefresh:function(){
                return "刷新";
            },
            formatToggle:function(){
                return "展開";
            },
            formatToggleOn:function(){
                return "顯示卡片視圖";
            },  
            formatToggleOff :function(){
                return "隱藏卡片視圖";
            },
            formatColumns:function(){
                return "列視圖";
            },
            formatColumnsToggleAll:function(){
                return 'Toggle all';
            },
            formatFullscreen:function(){
                return '全屏';
            },
            formatAllRows: function(){
                return '全部';
            }
            // bootstrap-table-treetreegrid.js 插件配置 -- end
        });
    });

    // 格式化按鈕
    function operateFormatter(value, row, index) {
        return [
            '<button type="button" class="RoleOfadd btn-small  btn-primary" style="margin-right:15px;"><i class="fa fa-plus" ></i>&nbsp;新增</button>',
            '<button type="button" class="RoleOfedit btn-small   btn-primary" style="margin-right:15px;"><i class="fa fa-pencil-square-o" ></i>&nbsp;修改</button>',
            '<button type="button" class="RoleOfdelete btn-small   btn-primary" style="margin-right:15px;"><i class="fa fa-trash-o" ></i>&nbsp;刪除</button>'
        ].join('');

    }
    // 格式化類型
    function typeFormatter(value, row, index) {
        if (value === 'menu') {  return '菜單';  }
        if (value === 'button') {  return '按鈕'; }
        if (value === 'api') {  return '接口'; }
        return '-';
    }
    // 格式化狀態
    function statusFormatter(value, row, index) {
        if (value === 1) {
            return '<span class="label label-success">正常</span>';
        } else {
            return '<span class="label label-default">鎖定</span>';
        }
    }

    //初始化操作按鈕的方法
    window.operateEvents = {
        'click .RoleOfadd': function (e, value, row, index) {
            add(row.id);
        },
        'click .RoleOfdelete': function (e, value, row, index) {
            del(row.id);
        },
        'click .RoleOfedit': function (e, value, row, index) {
            update(row.id);
        }
    };
</script>
<script>
    /**
     * 選中父項時,同時選中子項
     * @param datas 所有的數據
     * @param row 當前數據
     * @param id id 字段名
     * @param pid 父id字段名
     */
    function selectChilds(datas,row,id,pid,checked) {
        for(var i in datas){
            if(datas[i][pid] == row[id]){
                datas[i].check=checked;
                selectChilds(datas,datas[i],id,pid,checked);
            };
        }
    }

    function selectParentChecked(datas,row,id,pid){
        for(var i in datas){
            if(datas[i][id] == row[pid]){
                datas[i].check=true;
                selectParentChecked(datas,datas[i],id,pid);
            };
        }
    }

    function test() {
        var selRows = $table.bootstrapTable("getSelections");
        console.log(selRows);
        if(selRows.length == 0){
            alert("請至少選擇一行");
            return;
        }
        var postData = "";
        $.each(selRows,function(i) {
            postData +=  this.menuId;
            if (i < selRows.length - 1) {
                postData += ", ";
            }
        });
        alert("你選中行的 id 爲:"+postData);
    }

    function add(id) {
        alert("add 方法 , id = " + id);
    }
    function del(id) {
        alert("del 方法 , id = " + id);
    }
    function update(id) {
        alert("update 方法 , id = " + id);
    }
    
    function contains(sorce,str){
        if(null == sorce || undefined == sorce) return false;
        if(null == str || undefined == str) return false;
        return sorce.indexOf(str) != -1;
    }


</script>
</html>

參考鏈接:https://blog.csdn.net/Jason_M_Ho/article/details/82590145

                  https://www.bootstrap-table.com.cn/doc/api/methods/

                  http://www.itxst.com/Bootstrap-Table/rvfbrnva.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章