bootstrap table插件


10103.png

Bootstrap Table

官网

bootstrap tablebootstrap的一个表格插件.

访问官网Bootstrap Table)获取更多的支持.

演示

ajax返回数据

Bootstrap TableAJAX功能通常与服务器端的数据交互,返回的数据格式通常是JSON,因为JSON 是一种轻量级的数据交换格式,易于解析和生成。以下是 JSON 返回数据的基本结构,用于填充Bootstrap Table 的表格:

{
    "code": 200,
    "data": {
        "rows": [
            {
                "contact_info": "zhangsan@example.com",
                "name": "张三",
                "position": "技术总监"
            },
            {
                "contact_info": "lisi@example.com",
                "name": "李四",
                "position": "软件工程师"
            },
            {
                "contact_info": "wangwu@example.com",
                "name": "王五",
                "position": "测试工程师"
            },
            {
                "contact_info": "zhaoliu@example.com",
                "name": "赵六",
                "position": "市场总监"
            },
            {
                "contact_info": "qianqi@example.com",
                "name": "钱七",
                "position": "销售经理"
            },
            {
                "contact_info": "sunba@example.com",
                "name": "孙八",
                "position": "人力资源经理"
            },
            {
                "contact_info": "zhoujiu@example.com",
                "name": "周九",
                "position": "财务总监"
            },
            {
                "contact_info": "wushi@example.com",
                "name": "吴十",
                "position": "会计"
            }
        ],
        "total": 8,// 总记录数
        "totalNotFiltered": 8 // 分页pagination需要这个选项
    },
    "message": "success"
}
// rows中的内容是需要返回给前端的数据
  • total:总数
  • totalNotFiltered:分页时需要,参考
  • rows: 是一个数组,每个元素代表表格中的一行数

常用属性方法

定义在初始化方法中,可以定义在创建时

属性默认值描述创建
pageNumber1初始化加载第一页,默认为1data-page-number
paginationfalse是否显示分页data-pagination
sidePaginationclient分页方式,client前端,server后端data-side-pagination
pageSize10每页的行数data-page-size
pageList[10,25,50,100]可供选择的每页行数data-page-list
clickToSelectfalse点击选中行data-click-to-select
halignundefined[‘center,left,right’]表头的对齐方式data-halign
alignundefined[‘center,left,right’]数据的对齐方式data-align
clickToSelectfalse点击选中行data-click-to-select
classestable,table-bordered,table-hover表格的类名称data-classes
ajaxundefiend自定义ajax方法data-ajax
showColumnsfalse显示所有的列data-show-columns
toolbarundefiend指定工具栏data-toolbar
searchfalse显示搜索data-search
showRefreshfalse显示刷新data-show-refresh
showFooterfalse显示脚注data-show-footer

ajax请求

10103.png

一个典型的Ajax请求

<table id="listDepolyees" data-click-to-select="true" style="text-align: center;"
data-ajax="ajaxListDepolyees" data-show-columns="true" data-search="true"
data-show-refresh="true" data-show-footer="true"
data-classes="table table-bordered table-hover table-sm">
</table>

生成表格时指定data-ajax

在JavaScript中初始化表格,并指定ajax

<script>
    $(document).ready(function () {
    /*
            * bootstarp-table 显示
            */
    const listDepolyees = $('#listDepolyees');
    listDepolyees.bootstrapTable({
        columns: [
            { field: 'status', checkbox: true },
            { field: 'name', title: '姓名', sortable: true, halign: 'left', align:'right'},
            { field: 'position', title: '职位', sortable: true, halign: 'center'},
            { field: 'contact_info', title: '联系', sortable: true, halign: 'right', align:'left'},
        ]
    });
})
// bootstrap-table ajax获取数据
function ajaxListDepolyees(params) {
    $.ajax({
        url: 'http://127.0.0.1:5000/api/v1/deployees',
        type: 'GET',
        contentType: 'application/json',
        success: function (rst) {
            params.success(rst.data);
        },
        async: false
    })
}
</script>

分页

分页必须指定以下几项

  • data-pagination="true" : 开启分页

可以指定详细信息

  • data-page-size=2: 指定每页显示的条目
  • data-page-list="[10, 25, 50, 100, all]": 指定单页显示的条目数

10104.png

生成树结构

10105.png

生成树结构需要配合使用treegridbootstrap-table-treegrid扩展插件

  • treegrid: 参考 (https://maxazan.github.io/jquery-treegrid/)
  • bootstrap-table-treegrid: https://bootstrap-table.com/docs/extensions/treegrid/

需要的属性选项

option默认描述
data-tree-enablefalse为true时开启树形插件
data-id-fieldundefined指定哪个字段为childId,比如id
data-parent-id-fieldundefined指定parentId,比如pid
data-tree-show-fieldundefined指定字段上显示树,比如name
data-root-parent-idnullroot parent id

返回的数据.和基本的bootstrap-table返回的数据大致相同,唯一不同的是需要提供指定的idpid.

这样前端才能返回相关数据.

{
    "code": 200,
    "data": {
        "rows": [
            {
                "id": 1,
                "leader": "吴十",
                "pid": 0
            },
            {
                "id": 2,
                "leader": "张三",
                "pid": 1
            },
            {
                "id": 3,
                "leader": "李四",
                "pid": 1
            },
            {
                "id": 4,
                "leader": "王五",
                "pid": 1
            },
            {
                "id": 5,
                "leader": "赵六",
                "pid": 2
            },
            {
                "id": 6,
                "leader": "钱七",
                "pid": 2
            },
            {
                "id": 7,
                "leader": "孙八",
                "pid": 4
            },
            {
                "id": 8,
                "leader": "周九",
                "pid": 4
            }
        ],
        "total": 8,
        "totalNotFiltered": 8
    },
    "message": "success"
}

table : data-tree-enable="true" data-id-field="id" data-parent-id-field="pid" data-tree-show-field="name" 开启tree,设置cid,pid,显示在name

<table id="listDepartment" data-click-to-select="true" style="text-align: center;"
data-ajax="ajaxListDepartment" data-tree-enable="true" data-id-field="id"
data-parent-id-field="pid" data-tree-show-field="name"
data-classes="table table-bordered table-hover table-sm"></table>
$(document).ready(function () {
  /*
  * bootstarp-table 显示
  */
  const listDepartment = $('#listDepartment');
  listDepartment.bootstrapTable({
  columns: [
    { field: 'status', checkbox: true },
    { field: 'name', title: '姓名', sortable: true, halign: 'left', align: 'left' },
    { field: 'leader', title: '领导', sortable: true, halign: 'center' },
    ],
  onPostBody: function () {
    var columns = listDepartment.bootstrapTable('getOptions').columns;
    if (columns && columns[0][1].visible) {
      listDepartment.treegrid({
        treeColumn: 1,
        //initialState: "collapsed", 默认展开,collapsed则是折叠
        onChange: function () {
          listDepartment.bootstrapTable('resetView')
        }
      });
    }
  }
})
// ajax请求
function ajaxListDepartment(params){
    $.ajax({
        url: 'http://127.0.0.1:5000/api/v1/department',
        type: 'GET',
        contentType: 'application/json',
        success: function (rst) {
            params.success(rst.data);
        },
        async: false
    })
}    

formatter

10106.png

可以在初始化单元格是指定formatter,这个方法可以格式化table一列的数据.

<style>
    .structure{
        background: url("./img/sn-bg-dark.png") 0px 2px;
    }
</style>

<table id="listDepartmentFormatter" data-click-to-select="true" style="text-align: center;" data-ajax="ajaxListDepartmentFormatter" data-tree-enable="true" data-id-field="id" data-parent-id-field="pid" data-tree-show-field="name"
data-classes="table table-bordered table-hover table-sm"></table>
$(document).ready(function () {
  /*
  * bootstarp-table 显示
  */
  const listDepartmentFormatte = $('#listDepartmentFormatte');
  listDepartmentFormatte.bootstrapTable({
  columns: [
    { field: 'status', checkbox: true },
    { field: 'name', title: '姓名', sortable: true, halign: 'left', align: 'left', formatter: 'nameFormatter' },
    { field: 'leader', title: '领导', sortable: true, halign: 'center' },
    ],
  onPostBody: function () {
    var columns = listDepartment.bootstrapTable('getOptions').columns;
    if (columns && columns[0][1].visible) {
      listDepartmentFormatte.treegrid({
        treeColumn: 1,
        //initialState: "collapsed", 默认展开,collapsed则是折叠
        onChange: function () {
          listDepartmentFormatte.bootstrapTable('resetView')
        }
      });
    }
  }
})
// ajax请求
function ajaxListDepartmentFormatte(params){
    $.ajax({
        url: 'http://127.0.0.1:5000/api/v1/department',
        type: 'GET',
        contentType: 'application/json',
        success: function (rst) {
            params.success(rst.data);
        },
        async: false
    })
} 
// Formatter
function nameFormatter(value, row, index) {
// console.log(value, row, index);
if (row['pid'] == 0) {
 return ['<i class="fa fa-folder-open"/>' + value]
} else {
 return ['<span class="structure" style="padding-left:10px; margin-left:0px;" style="padding-left:10px; margin-left:0px;"></span>' + value]
}
}    

events

10107.png

events 可以为bootstrap-table中的一列添加事件,比如操作事件(添加,删除)等等.

events中接受jQuery语句.

<style>
    .operate-edit {
        margin-left: 1px;
    }

    .operate-delete {
        margin-left: 1px;
    }
</style>

<table id="listDepolyeesEvents" data-click-to-select="true"
       style="text-align: center;" data-url="./json/data1.json"
       data-pagination="true" data-page-list="[4, 6, all]" data-page-size="2"
       data-classes="table table-bordered table-hover table-sm">
</table>
$(document).ready(function () {
  /*
  * bootstarp-table 显示
  */
    const listDepolyeesEvents = $('#listDepolyeesEvents');
    listDepolyeesEvents.bootstrapTable({
        columns: [
            { field: 'status', checkbox: true },
            { field: 'name', title: '姓名', sortable: true, halign: 'left', align: 'right' },
            { field: 'position', title: '职位', sortable: true, halign: 'center' },
            { field: 'operate', title: '操作', clickToSelect: false, formatter: 'operateFormatter', events: 'operateEvents' }
        ]
    });   
})

// formatter
function operateFormatter(value, row, index){
    return [
        '<div class="btn-group">',
        '<button type="button" class="btn btn-default btn-xs operate-edit"><i class="fa fa-pencil-alt"></i></button>',
        '<button type="button" class="btn btn-default btn-xs operate-delete"><i class="fa fa-times"></i></button>',
        '</div>'].join('')
}
//events
window.operateEvents = {
    'click .operate-edit': function (e, value, row, index) {
        // 可以写jQuery语句
        alert(JSON.stringify(row));
    },
    'click .operate-delete' :  function (e, value, row, index){
        alert(JSON.stringify(row));
    }
}

隐藏某一列

visible: false //这一列隐藏

模态框多次打开

点击测试

模态框多次打开,提交会提交所有打开的内容.

这里使用了bootstrap-tableformat,所以只能写在window.oprateEvents中,如果在这里写modalsubmit事件,会提交多次,只要把他放在jquery中就可以了.

<table id="listModal" data-click-to-select="true"
       style="text-align: center;" data-url="./json/data1.json" data-pagination="true"
       data-page-list="[4, 6, all]" data-page-size="2"
       data-classes="table table-bordered table-hover table-sm">
</table>

<div class="modal fade" id="modal-editEmp">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- 竖排表单 -->
                <div class="card">
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form class="form-horizontal" method="post">
                        <div class="card-body">
                            <div class="form-group row">
                                <label for="editName" class="col-sm-2 col-form-label">姓名</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control" id="editName" placeholder="姓名">
                                </div>

                            </div>
                            <div class="form-group row">
                                <label for="editDep" class="col-sm-2 col-form-label">职位</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control" id="editDep" placeholder="职位">
                                </div>

                            </div>

                            <!-- /.card-body -->
                            <!-- /.card-footer -->
                            </form>
                        </div>
                    <!-- /.card -->

                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary submitEdit" id="submitEdit">保存修改</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
// formatter
function operateFormatterM(value, row, index) {
    return [
        '<div class="btn-group">',
        '<button type="button" class="btn btn-default btn-xs operate-edit1"><i class="fa fa-pencil-alt"></i></button>',            
        '</div>'].join('')
}
//events
window.operateEventsM = {
    'click .operate-edit1': function (e, value, row, index) {
        // 可以写jQuery语句

        // 模态框弹出之前
        $('#modal-editEmp').on('show.bs.modal', function () {
            $('#editName').val(row['name']);
            $('#editDep').val(row['position']);
        });
        // 弹出模态框
        $('#modal-editEmp').modal('show');
        // 提交数据

        $('#submitEdit').click(function(e){
            e.preventDefault();
            const name = $('#editName').val();
            const position = $('#editDep').val();
            console.log(name, position);
            alert(JSON.stringify(row));
        })

    }
}

如果写在window.operateEventsM中,会多次提交.分开提交只有一次提交

如下:

$(document).ready(function () {
    const listModal = $('#listModal');
    listModal.bootstrapTable({
        columns: [
            { field: 'status', checkbox: true },
            { field: 'name', title: '姓名', sortable: true, halign: 'left', align: 'right' },
            { field: 'position', title: '职位', sortable: true, halign: 'center' },
            { field: 'operateM', title: '操作', clickToSelect: false, formatter: 'operateFormatterM', events: 'operateEventsM' }
        ]
    });
/*
* 提交
*/
    $('#submitEdit').click(function(e){
        e.preventDefault();
        const name = $('#editName').val();
        const position = $('#editDep').val();
        console.log(name, position);
        //alert(JSON.stringify(row));
    })
})
// formatter
function operateFormatterM(value, row, index) {
    return [
        '<div class="btn-group">',
        '<button type="button" class="btn btn-default btn-xs operate-edit1"><i class="fa fa-pencil-alt"></i></button>',            
        '</div>'].join('')
}
//events
window.operateEventsM = {
    'click .operate-edit1': function (e, value, row, index) {
        // 可以写jQuery语句

        // 模态框弹出之前
        $('#modal-editEmp').on('show.bs.modal', function () {
            $('#editName').val(row['name']);
            $('#editDep').val(row['position']);
        });
        // 弹出模态框
        $('#modal-editEmp').modal('show');
    }
}

文章作者: 文彦
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 文彦 !
评论
  目录