bootstrap-table使用详解

尴尬,标记果然到了一周之后。。。。

 

首先引入文件不必提,引入bootstrap和bootstrap-table

<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-table.css">
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="bootstrap-table.js"></script>
<-- put your locale files after bootstrap-table.js -->
<script src="bootstrap-table-zh-CN.js"></script>

有三种设置table的方式,以下:

1、对于静态的可以直接设置table

<table data-toggle="table">
    <thead>
        <tr>
            <th>Item ID</th>
            <th>Item Name</th>
            <th>Item Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Item 1</td>
            <td>$1</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Item 2</td>
            <td>$2</td>
        </tr>
    </tbody>
</table>

2、设置远程的链接渲染table

<table data-toggle="table" data-url="data1.json">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name" data-width="60">Item Name</th>
            <th data-field="price"  data-formatter="functionName">Item Price</th>
        </tr>
    </thead>
</table>
这里的field是根据远程连接返回的不同key值来设置的,
data-width:设置这一列的宽度
data-formatter 设置的是这一列渲染的展示方法,如下:

function vestSatusFormatter(val,row,index){
if(val)
return '<span title="'+val+'" >'+val+'</span>'

else 

return '无数据'
}  

val对应这个field返回的值,row是这一行的所有数据,index对应的第几条数据(从0开始),return 返回的即前台用户看到的呈现结果;

 
 

3、通过table的id设置

<table id="table" data-url="data1.json"></table> 
$('#table').bootstrapTable('destroy').bootstrapTable({
 url: 'data1.json', // 改变当前table的链接 ,请求后台的URL(*)可以不需要
method: 'post',    //请求方式(*)
toolbar: toolbar, //工具按钮用哪个容器
striped: true, //是否显示行间隔色
cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination: true, //是否显示分页(*)
sortable: false, //是否启用排序
sortOrder: "asc", //排序方式
queryParams: queryParams, //传递参数(*),这里应该返回一个object,即形如{param1:val1,param2:val2}
sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
pageNumber:1, //初始化加载第一页,默认第一页
pageSize: 20, //每页的记录行数(*)
pageList: [20, 50, 100], //可供选择的每页的行数(*)
columns: [{
        field: 'id',
        title: 'Item ID'
    }, {
        field: 'name',
        title: 'Item Name'
    }, {
        field: 'price',
        title: 'Item Price'
    }, ]
});

  根据搜索条件刷新table

$("#"+domId).bootstrapTable('destroy').bootstrapTable({
        striped:true,
        sidePagination: 'server',
        pagination:true,
        pageSize: 10,
        pageList: [10, 20, 50, 100, 200,400],
        queryParams: function(param){
            var query;  
            if(type && search){
                params['searchType'] = “你的搜索值”;
                params['searchContent'] = "你的搜索值";
            };
            query=params;
            $.extend(query,param);            
            return query;
        },
        formatLoadingMessage: function(){
          return '正在加载...';
        },
        formatNoMatches: function(){
          return '没有找到数据~';
        },
        formatShowingRows: function(pageFrom, pageTo, totalRows){
          return '共'+totalRows+'条,显示'+pageFrom+'到'+pageTo+'条记录';
        },
        formatRecordsPerPage: function (pageNumber) {
             return '每页显示 ' + pageNumber + ' 条记录';
        }
      });

另外的是涉及到后台返回的参数跟原框架的不同,修改

修改方法
 responseHandler:function (res) {
            return {
                rows:res.list  //返回的数据详情
                total:res.total_count, //总条数
            };
        },                

 

涉及到保存分页的问题可能会修改bootstrap-table.js源码,主要用到一个方法$(table).bootstrapTable('getOptions')

在js里定义原型方法 

BootstrapTable.prototype.getPage = function (params) { 
  return {pageSize: this.options.pageSize, pageNumber: this.options.pageNumber};
}; //这个只是提供更简洁的一种方法,不一定需要,看个人情况

并且定义该方法 大概在3015行左右

var allowedMethods = [
'getOptions','getPage',
'getSelections', 'getAllSelections', 'getData'

...

]

-----------------------------

下面可以利用该方法

function setOptions(table,sessionName) { //获取到当前页码的相关信息 var options = $(table).bootstrapTable('getOptions'), Obj = { "limit":options.pageSize, "offset":(options.pageNumber - 1)*options.pageSize, "sort":options.sortName, "order":options.sortOrder }; }

最后的是一点展示方面的问题,毕竟是一枚前端仔,你懂得,

有些table比较高可以设置height控制头部固定,但是会影响拖拽的效果所以要加这一句

<table id="table" class="data-table" data-height="600" ></table> 
$(window).resize(function () {
      $('#table').bootstrapTable('resetView');
   });

当然,如果你的th需要换行,需要这些设置

#table{
  table-layout: fixed;
}
#tabletd{
   word-break:break-all;
   word-wrap:break-word;
}
.fixed-table-container thead th .th-inner{
    white-space: pre-line !important;
}

 

暂时想到的只有这些,如果有什么不对的地方欢迎指出,蟹蟹~

 

转载于:https://www.cnblogs.com/simba-lkj/p/8909378.html

JS组件Bootstrap Table使用方法详解 转载 2016年03月21日 15:06:09 标签: Bootstrap Table 最近客户提出需求,想将原有的管理系统,做下优化,通过手机也能很好展现,想到2个方案: a方案:保留原有的页面,新设计一套适合手机的页面,当手机访问时,进入m.zhy.com(手机页面),pc设备访问时,进入www.zhy.com(pc页面) b方案:采用bootstrap框架,替换原有页面,自动适应手机、平板、PC 设备 采用a方案,需要设计一套界面,并且要得重新写适合页面的接口,考虑到时间及成本问题,故项目采用了b方案 一、效果展示 二、BootStrap table简单介绍 bootStrap table 是一个轻量级的table插件,使用AJAX获取JSON格式的数据,其分页和数据填充很方便,支持国际化 三、使用方法 1、引入js、css [js] view plain copy <!--css样式--> <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap/bootstrap-table.css" rel="stylesheet"> <!--js--> [removed][removed] [removed][removed] [removed][removed] [removed][removed] 2、table数据填充 bootStrap table获取数据有两种方式,一是通过table 的data-url属性指定数据源,二是通过JavaScript初始化表格时指定url来获取数据 [xhtml] view plain copy ... ... [xhtml] view plain copy $('#table').bootstrapTable({ url: 'data.json' }); 第二种方式交第一种而言在处理复杂数据时更为灵活,一般使用第二种方式来进行table数据填充。 [js] view plain copy $(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); //2.初始化Button的点击事件 /* var oButtonInit = new ButtonInit(); oButtonInit.Init(); */ }); var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#tradeList').bootstrapTable({ url: '/VenderManager/TradeList', //请求后台的URL(*) method: 'post', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: false, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber:1, //初始化加载第一页,默认第一页 pageSize: 50, //每页的记录行数(*) pageList: [10, 25, 50, 100], //可供选择的每页的行数(*) strictSearch: true, clickToSelect: true, //是否启用点击选中行 height: 460, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "id", //每一行的唯一标识,一般为主键列 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 columns: [{ field: 'id', title: '序号' }, { field: 'liushuiid', title: '交易编号' }, { field: 'orderid', title: '订单号' }, { field: 'receivetime', title: '交易时间' }, { field: 'price', title: '金额' }, { field: 'coin_credit', title: '投入硬币' }, { field: 'bill_credit', title: '投入纸币' }, { field: 'changes', title: '找零' }, { field: 'tradetype', title: '交易类型' },{ field: 'goodmachineid', title: '货机号' },{ field: 'inneridname', title: '货道号' },{ field: 'goodsName', title: '商品名称' }, { field: 'changestatus', title: '支付' },{ field: 'sendstatus', title: '出货' },] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 sdate: $("#stratTime").val(), edate: $("#endTime").val(), sellerid: $("#sellerid").val(), orderid: $("#orderid").val(), CardNumber: $("#CardNumber").val(), maxrows: params.limit, pageindex:params.pageNumber, portid: $("#portid").val(), CardNumber: $("#CardNumber").val(), tradetype:$('input:radio[name="tradetype"]:checked').val(), success:$('input:radio[name="success"]:checked').val(), }; return temp; }; return oTableInit; }; field字段必须与服务器端返回的字段对应才会显示出数据。 3、后台获取数据 a、servlet获取数据 [js] view plain copy BufferedReader bufr = new BufferedReader( new InputStreamReader(request.getInputStream(),"UTF-8")); StringBuilder sBuilder = new StringBuilder(""); String temp = ""; while((temp = bufr.readLine()) != null){ sBuilder.append(temp); } bufr.close(); String json = sBuilder.toString(); JSONObject json1 = JSONObject.fromObject(json); String sdate= json1.getString("sdate");//通过此方法获取前端数据 ... b、springMvc Controller里面对应的方法获取数据 [js] view plain copy public JsonResult GetDepartment(int limit, int offset, string orderId, string SellerId,PortId,CardNumber,Success,maxrows,tradetype) { ... } 4、分页(遇到问题最多的) 使用分页,server端返回的数据必须包括rows和total,代码如下: [js] view plain copy ...gblst = SqlADO.getTradeList(sql,pageindex,maxrows); JSONArray jsonData=new JSONArray(); JSONObject jo=null; for (int i=0,len=gblst.size();i<len;i++) { TradeBean tb = gblst.get(i); if(tb==null) { continue; } jo=new JSONObject(); jo.put("id", i+1); jo.put("liushuiid", tb.getLiushuiid()); jo.put("price", String.format("%1.2f",tb.getPrice()/100.0)); jo.put("mobilephone", tb.getMobilephone()); jo.put("receivetime", ToolBox.getYMDHMS(tb.getReceivetime())); jo.put("tradetype", clsConst.TRADE_TYPE_DES[tb.getTradetype()]); jo.put("changestatus", (tb.getChangestatus()!=0)?"成功":"失败"); jo.put("sendstatus", (tb.getSendstatus()!=0)?"成功":"失败"); jo.put("bill_credit", String.format("%1.2f",tb.getBill_credit()/100.0)); jo.put("changes",String.format("%1.2f",tb.getChanges()/100.0)); jo.put("goodroadid", tb.getGoodroadid()); jo.put("SmsContent", tb.getSmsContent()); jo.put("orderid", tb.getOrderid()); jo.put("goodsName", tb.getGoodsName()); jo.put("inneridname", tb.getInneridname()); jo.put("xmlstr", tb.getXmlstr()); jsonData.add(jo); } int TotalCount=SqlADO.getTradeRowsCount(sql); JSONObject jsonObject=new JSONObject(); jsonObject.put("rows", jsonData);//JSONArray jsonObject.put("total",TotalCount);//总记录数 out.print(jsonObject.toString()); ... 5、分页界面内容介绍 前端获取分页数据,代码如下: [js] view plain copy ...oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //第几条记录 offset: params.offset, //显示一页多少记录 sdate: $("#stratTime").val(), }; return temp; };... 后端获取分页数据,代码如下: [js] view plain copy ...int pageindex=0; int offset = ToolBox.filterInt(json1.getString("offset")); int limit = ToolBox.filterInt(json1.getString("limit")); if(offset !=0){ pageindex = offset/limit; } pageindex+= 1;//第几页... 以上就是为大家分享的Bootstrap Table使用方法,希望对大家熟练掌握Bootstrap Table使用方法有所帮助。 转自:http://www.jb51.net/article/79033.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值