zoukankan      html  css  js  c++  java
  • 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) } }

    初次做封装这类的,不太熟,而且封装的很乱,很多的都没考虑周全,以后会接着改进

  • 相关阅读:
    TransactionScop事务机制的使用
    MVC无刷新上传图片并显示
    WebClient和WebRequest获取html代码
    Web.config配置详解
    分类和扩展有什么区别?可以分别用来做什么?分类有哪些局限性?分类的结构体里面有哪些成员?
    有序二维数组的查找
    生成Excel.xlsx文件 iOS
    charles Https抓包
    https 通信流程和Charles 抓包原理
    fastlane自动化打包ipa并发布到firim或者蒲公英
  • 原文地址:https://www.cnblogs.com/wsblogs/p/7738044.html
Copyright © 2011-2022 走看看