[转]bootstrap table 动态列数
原文地址:https://my.oschina.net/u/2356355/blog/1595563
據(jù)說bootstrap table非常好用,從入門教程中了解到它的以下主要功能:
由于固定表頭意味著固定的列,然而我需要做動態(tài)列數(shù)的表格啊。
大致思路:bootstrap table在加載表格時,表格的內(nèi)容按columns參數(shù)中的數(shù)組來填充。因此,通過動態(tài)地生成與columns參數(shù)中的數(shù)組,我們可以實現(xiàn)動態(tài)列名,也就是動態(tài)表格。
columns參數(shù)格式大致如下:
主要邏輯代碼:
通過Object.keys(obj)來獲取對象的key的名稱,除選項框外,key的數(shù)量對應(yīng)列的數(shù)量,在for循環(huán)中遍歷key的名稱,將key填充進(jìn)title,在銷毀后重新創(chuàng)建的bootstrapTable表中,填充好數(shù)據(jù)源json和columns參數(shù),實現(xiàn)動態(tài)擴展表格的列。
需要注意的是:這里的列名是英文的,如果需要中文的列名的話,最好接口中返回了中文列的名稱,將中文列名遍歷到一個空的數(shù)組中,再取出來填充在title屬性后。再有就是,由于所有的屬性都通過遍歷生成,所以列之間沒有差異性,需要通過jquery再豐富一下列的功能。
我的json數(shù)據(jù)如下:
我的表格html:
<%--bootstrap table + ajax--%> <div><table id="table" class="table table-responsive table-striped table-bordered table-hover table-condensed "></table> </div>完整js代碼:
$("#table").bootstrapTable({ajax: function (request) {$.ajax({type: "GET",url: "/table",contentType: "application/json;charset=utf-8",dataType: "json",json: 'callback',success: function (json) {var columnsArray = [];columnsArray.push({field: "state", checkbox: true});for (var i = 0; i < (Object.keys(json[0])).length; i++) {//Object.keys(obj) 獲取key名稱var property = (Object.keys(json[0]))[i];//id usernamecolumnsArray.push({"title": property,"field": property,switchable: true,sortable: true});}$('#table').bootstrapTable('destroy').bootstrapTable({data: json,toolbar: '#toolbar',singleSelect: true,clickToSelect: true,sortName: "create_time",sortOrder: "desc",pageSize: 15,pageNumber: 1,pageList: "[10, 25, 50, 100, All]",showToggle: true,showRefresh: true,showColumns: true,search: true,pagination: true,columns: columnsArray});},error: function () {alert("錯誤");}});}});表格數(shù)據(jù)加載效果如下:
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的[转]bootstrap table 动态列数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mui页面交互
- 下一篇: 用vue制作饿了么首页(1)