bootstrap-table


用到了bootstrap-table插件,瞬間感覺打開了新世界大門!之前感覺table啥的樣式特別不好搞,用了這個插件以后,覺得根本不是事!!!

官網文檔:http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

下載地址:http://bootstrap-table.wenzhixin.net.cn/zh-cn/getting-started/

文檔上面解釋的很詳細,各種各樣的功能。

實現table的方式有兩種,一種在html里就可以實現,一種通過js。兩種都很方便!

   <table id="table"
                       data-toggle="table"
                       data-striped="true"
                       data-toolbar="#toolbar"
                       data-pagination="true"
                       data-page-size="10"
                       data-show-refresh="true"
                       data-show-columns="true"
                       data-select-item-name="id"
                       data-show-pagination-switch="false"
                       data-unique-id="id"

                >
                    <thead>
                        <tr>
                            <th data-checkbox="true"></th>
                            <th data-field="id"  data-sortable="true">Item ID</th>
                            <th data-field="name"  data-visible="false">Item Name</th>
                            <th data-field="price">Item Price</th>
                            <th data-field="num">Item num</th>
                            <th data-field="maker" data-sortable="true">Item maker</th>
                            <th data-field="warehouse">Item warehouse</th>
                            <th data-field="city">Item city</th>
                            <th data-field="isuse">Item isuse</th>
                            <th data-field="time">Item time</th>
                            <th data-field="tips">Item tips</th>
                            <th data-formatter="AddFunctionAlty" data-events="operateEvents"></th>
                        </tr>
                    </thead>
                </table>

 

 

表格參數寫在table標簽中,例如<table data-url='data/data.json'></table>,作為表格的屬性,下面這次用到的表格參數的說明:

屬性 默認值 解釋
data-toggle table 這是必須的一個屬性,告訴扮演的是一個表格,官網的解釋是,不用寫js直接啟用表格
data-url undefined 服務器請求地址,就是平時ajax寫的url
data-method get 請求服務器方式,get post
data-striped

false

為true時表格會出現隔行變色效果
data-toolbar undefined 指定工具欄,自定義工具欄 類似jquery選擇器   #toolbar
data-pagination false 為true的時候,表格底部會有分頁
data-page-size 10 一頁有多少條數據
data-show-refresh false

為true的時候顯示刷新按鈕,是一個小圖標,需要引入 bootstrap里面的glyphicons字體庫,注意層級關系

data-show-columns false

為true的時候顯示內容下拉框,選擇哪列顯示,哪里隱藏,在這里的隱藏是在表格中直接remove掉,獲取不到的。顯示數據再次插入

data-uniqueId undefined

指定哪個列作為主鍵 tips:最好寫上,方法上有好幾個都要用到uniqueId

data-field ''

設置數據來源字段的名稱,與服務器端返回來的數據中的數據字段保持一致

data-side-pagination
'client'

設置‘server’后必須設置服務器數據地址,返回的數據中也必須有相關的分頁字段,如total


更詳細的說明參考bootstrap-table官方文檔。

bootstrap-table還有一個插件叫 bootstrap-table-fixed-columns.js用來凍結表頭、凍結列的,十分好用。

引入bootstrap-table-fixed-columns.js之前需要引入bootstrap.min.js和bootstrap-table.min.js 及其各個的css文件。

使用方法在表格參數部分加上  fixedColumns: true, fixedNumber: 0,即可

 $("#"+this.table).bootstrapTable({
            url:'../data/bootstrap-table.json',
            method:'get',//使用get方式請求服務器獲取數據
            queryParamsType : "",
            dataField:"data",
            queryParams:params=>{
                this.param=this.getFormJson(this.formId)
                this.param["pageSize"] = params.pageSize;
                this.param["pageNumber"] = params.pageNumber
                this.param['order'] = params.order;
                this.param['limit'] = params.limit;
                return this.param ;
            },
            onLoadSuccess: function(){  //加載成功時執行

            },
            onLoadError: function(){  //加載失敗時執行

            },
            sidePagination : "server",
            fixedColumns: true,
            fixedNumber: 0,
            height:getHeight()
        });

 

列參數:

屬性 默認值 解釋
 data-checkbox   false  生成一個復選框列,這個復選框列有固定的寬度
 data-field  ‘’    當前列的名字,綁定數據字段
 data-visible      true            當前列默認隱藏還是顯示                      
 data-formatter undefined  這個屬性接收的是一個函數,這個函數有三個參數,value,row,index,返回值為列的內容。一般用來添加操作列,具體見代碼
 data-events undefined 為列添加事件,具體代碼
 //將需要創建的按鈕封裝在函數里
    function AddFunctionAlty(value,row,index){
        return [
            "<a class='btn btn-xs btn-primary'><i class='fa fa-eye'></i> 查看</a> " +
            "<a class='btn btn-xs btn-info tableEditor'><i class='glyphicon glyphicon-edit'></i> 編輯</a> " +
            "<a  class='btn btn-xs btn-danger tableDelete'><i class='glyphicon glyphicon-trash'></i> 刪除</a>"
        ]
    }
    window.operateEvents = {
        'click .tableEditor': function (e, value, row, index) {
            alert('editor, row: ' + JSON.stringify(row));
        },
        'click .tableDelete': function (e, value, row, index) {
            //刪除指定行
            $("#table").bootstrapTable('removeByUniqueId',row.id )
            //無參數刷新
            // $("#table").bootstrapTable('refresh');
            //帶參數刷新
            var opt = {
                url: "../data/bootstrap-table-delect.json",
                silent: true, //靜默刷新
                query:{
                    //請求參數
                    name:$("#name").val(),
                    area:$("#area").val()
                }
            };
            $("#table").bootstrapTable('refresh', opt);
        }
    }    

方法:

1、獲取選中的checkbox         $('#table').bootstrapTable('getSelections')

2、刷新表格       

      a.   $('#table').bootstrapTable('refresh')

   b.    

            var opt = {
                url: "../data/bootstrap-table-delect.json", silent: true, //靜默刷新  query:{ //請求參數 name:$("#name").val(), area:$("#area").val() } }; $("#table").bootstrapTable('refresh', opt);

3、刪除選中行

  $("#table").bootstrapTable('removeByUniqueId',id )

4、批量刪除

//批量刪除
var ids = $.map($("#table").bootstrapTable('getSelections'), function (row) {
return row.id
});
if(ids.length==0){
alert("至少選擇一行!")
}else{
if(confirm("確定要刪除選中項?")){
$("#table").bootstrapTable('remove', {
field: 'id',
values: ids
});
}

}

 下面上代碼:

html

<!DOCTYPE html>
<!--[if IE 8]>
<html lang="zh" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="zh">
<!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>bootstrap-table</title>
    <link href="../statics/js/bootstrap-table/css/bootstrap.min.css" rel="stylesheet">
    <link href="../statics/js/bootstrap-table/css/bootstrap-table.min.css" rel="stylesheet">
    <link href="../statics/js/bootstrap-table/css/bootstrap-table-fixed-columns.css" rel="stylesheet">

    <!-- ======基礎樣式結束======-->
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="../statics/js/bootstrap/html5shiv.js"></script>
    <script src="../statics/js/bootstrap/respond.min.js"></script>
    <![endif]-->

</head>
<body>
<div class="contentpanel">
    <div class="panel panel-default">
        <div class="panel-heading">
            <div class="panel-btns"><a href="#" class="minimize">−</a></div>
            <h4 class="panel-title">查詢</h4>
        </div>
        <div class="panel-body">
            <form action="" class="form-horizontal " id="form1">
                <div class="row">
                    <div class="col-sm-6 col-md-4 mb15">
                        <div class="form-group">
                            <label class="control-label col-xs-5">倉庫名稱:</label>

                            <div class="col-xs-7">
                                <input type="text" class="form-control" placeholder="請輸入名稱"  id="name" >
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-4 mb15">
                        <div class="form-group">
                            <label class="control-label col-xs-5">倉庫所在區:</label>
                            <div class="col-xs-7">
                                <select name="" id="area" class="form-control" >
                                    <option value="">啟用</option>
                                    <option value="">停用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-3 mb15 pull-right text-right">
                        <a href="#" class="btn btn-primary" id="search"><i class="fa fa-search"></i> 查詢</a>
                    </div>
                </div>
                <!-- row-->

            </form>

        </div>

    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title" >倉庫列表</h4>
            <div id="toolbar">
                <button type="button" class="btn btn-default" id="getSelections">
                    <i class="glyphicon glyphicon-check"></i>
                    獲取選中
                </button>
                <button type="button" class="btn btn-danger" id="batchDeletion">
                    <i class="glyphicon glyphicon-trash"></i>
                    批量刪除
                </button>
                <button type="button" class="btn btn-primary" id="Added">
                    <i class="glyphicon glyphicon-plus"></i>
                    新增
                </button>
                <button type="button" class="btn btn-info" id="Export"  data-toggle="modal" data-target="#myModal">
                    <i class="glyphicon glyphicon-share-alt"></i>
                    導出
                </button>
            </div>
        </div>
        <div class="panel-body">
            <div class="table-responsive" id="goodsList">

                <table id="table"
                       data-toggle="table"
                       data-striped="true"
                       data-toolbar="#toolbar"
                       data-pagination="true"
                       data-page-size="10"
                       data-show-refresh="true"
                       data-show-columns="true"
                       data-select-item-name="id"
                       data-show-pagination-switch="false"
                       data-unique-id="id"

                >
                    <thead>
                        <tr>
                            <th data-checkbox="true"></th>
                            <th data-field="id"  data-sortable="true">Item ID</th>
                            <th data-field="name"  data-visible="false">Item Name</th>
                            <th data-field="price">Item Price</th>
                            <th data-field="num">Item num</th>
                            <th data-field="maker" data-sortable="true">Item maker</th>
                            <th data-field="warehouse">Item warehouse</th>
                            <th data-field="city">Item city</th>
                            <th data-field="isuse">Item isuse</th>
                            <th data-field="time">Item time</th>
                            <th data-field="tips">Item tips</th>
                            <th data-formatter="AddFunctionAlty" data-events="operateEvents"></th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">提示</h4>
            </div>
            <div class="modal-body">請選擇導出類型</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" onclick="table.export('../data/bootstrap-table.json',0)">導出顯示列</button>
                <button type="button" class="btn btn-primary" onclick="table.export('../data/bootstrap-table.json',1)">導出全部列</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<script src="../statics/js/bootstrap/jquery-1.11.1.min.js"></script>
<script src="../statics/js/bootstrap/bootstrap.min.js"></script>


<script src="../statics/js/bootstrap/jquery-ui-1.10.3.min.js"></script>

<script src="../statics/js/bootstrap-table/js/bootstrap-table.min.js"></script>
<script src="../statics/js/bootstrap-table/js/bootstrap-table-zh-CN.min.js"></script>
<script src="../statics/js/bootstrap-table/js/bootstrap-table-fixed-columns.js"></script>
<script src="../statics/js/bootstrap/bootstrap-table-default.js"></script>

<script>

    var table;
    $(function(){
        table=new $table(1,10,'form1')
        table.init('table','../data/bootstrap-table.json','get')
    })
    //將需要創建的按鈕封裝在函數里
    function AddFunctionAlty(value,row,index){
        return [
            "<a class='btn btn-xs btn-primary'><i class='fa fa-eye'></i> 查看</a> " +
            "<a class='btn btn-xs btn-info tableEditor'><i class='glyphicon glyphicon-edit'></i> 編輯</a> " +
            "<a  class='btn btn-xs btn-danger tableDelete'><i class='glyphicon glyphicon-trash'></i> 刪除</a>"
        ]
    }
    //為操作欄的編輯和刪除添加事件
    window.operateEvents = {
        'click .tableEditor': function (e, value, row, index) {
            alert('editor, row: ' + JSON.stringify(row));
        },
        'click .tableDelete': function (e, value, row, index) {
            table.rowDelete('../data/bootstrap-table-delect.json',row.id,"確定要刪除這一行?",true)
        }
    }
    //獲取選中的checkbox
    $("#getSelections").click(function(){
        alert(JSON.stringify($('#table').bootstrapTable('getSelections')))
    })
    //批量刪除
    $("#batchDeletion").click(function(){
        table.batchDeletion('../data/bootstrap-table-delect.json')
    })




</script>

</body>
</html>

 

bootstrap-table-default.js

//獲取表格的高度
function getHeight(){
    var h=parent.document.body.scrollHeight -document.body.clientHeight-90
    return h
}
function  $table(currentPage,numPerPage,formId){
  //currentPage 當前頁 numperPage 每頁條數 formId 頁面中查詢部分form id
this.currentPage=currentPage; this.numPerPage=numPerPage; this.formId=formId; this.param={} this.table='' this.url='' } $table.prototype={ init(table,url,type){ console.log(this) this.table=table; this.url=url; $("#"+this.table).bootstrapTable('destroy'); var t=$("#"+this.table).bootstrapTable({ url:'../data/bootstrap-table.json', method:'get',//使用get方式請求服務器獲取數據 queryParamsType : "", dataField:"data", queryParams:params=>{ this.param=this.getFormJson(this.formId) this.param["pageSize"] = params.pageSize; this.param["pageNumber"] = params.pageNumber this.param['order'] = params.order; this.param['limit'] = params.limit; return this.param ; }, onLoadSuccess: function(){ //加載成功時執行 }, onLoadError: function(){ //加載失敗時執行 }, sidePagination : "server", fixedColumns: true, fixedNumber: 0, height:getHeight() }); console.log(t) return t; }, refreshTable () { if (this.url == undefined) { $("#" + this.table).bootstrapTable('refresh') } else { param = getFormJson(this.formId) param["pageNum"] = this.currentPage; param["numPerPage"] = this.numPerPage; var opt = { url: this.url, silent: true, //靜默刷新 query: param }; $("#" + this.table).bootstrapTable('refresh', opt) } return this; }, getFormJson(id){ var o = {}; var a = $("#"+id).serializeArray(); $.each(a, function () { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }, rowDelete(url,id,message,isrefresh){ if( confirm(message)){ //刪除指定行 $.ajax({ url:url, type:'POST', data:{ }, dataType:'JSON', success:data=>{ $("#"+this.table).bootstrapTable('removeByUniqueId',id ) if(isrefresh){ //刷新table this.refreshTable() } } }) } }, batchDeletion(url){ //批量刪除 let ids = $.map($("#"+this.table).bootstrapTable('getSelections'), function (row) { return row.id }); if(ids.length==0){ alert("至少選擇一行!") }else{ if(confirm("確定要刪除選中項?")){ //刪除指定行 $.ajax({ url: url, type: 'POST', data: {}, dataType: 'JSON', success: data => { $("#" + this.table).bootstrapTable('remove', { field: 'id', values: ids }); } }) } } }, export(url,type){ //導出 if(type==0){ //獲取顯示列 var vc= $("#"+this.table).bootstrapTable('getVisibleColumns') }else{ //獲取全部列 var vc=$("#"+this.table).bootstrapTable('getOptions') vc=vc.columns[0]; } var vcJson=[] $.each(vc,function(index,value){ if((value.checkbox || value.radio) && index == 0 || value.title=="" ||value.title=="操作"){ }else{ var json={} json.key=value.field json.value=value.title vcJson.push(json) } }) var form = $("<form>"); form.attr('style', 'display:none'); form.attr('target', '_blank'); form.attr('method', 'post'); form.attr('action', url); $.each(this.param,function(key,value){ let input = $('<input>'); input.attr('type', 'hidden'); input.attr('name', key); input.attr('value', value); form.append(input); }) let input = $('<input>'); input.attr('type', 'hidden'); input.attr('name', 'columJson'); input.attr('value', vcJson); form.append(input); $('body').append(form); form.submit(); return JSON.stringify(vcJson) } }

初次做封裝這類的,不太熟,而且封裝的很亂,很多的都沒考慮周全,以后會接着改進


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM