首页 > 技术文章 > 前端开发 - Bootstraptable onPreBody()两次加载的问题

zhangnianlei 2018-11-11 22:46 原文

文档:

onPreBody pre-body.bs.table data 在表格 body 渲染之前触发。

简单解释:

重写onProBody()方法可以实现在表格渲染之前更改表格的数据

但是 onProBody()方法被运行了两次,

如下例:

function printTable(insertRow) {
    $table.bootstrapTable({
        method: "POST",
        cache: false,
        url: ctx + "/admin/cashierManager/getCashierDataList",
        contentType: "application/x-www-form-urlencoded",
        pageSize: 5,
        pageNumber: 1, 
        pageList: [5, 10, 20],
        dataSidePagination: "server",
        sidePagination: "server",
        dataType: 'json',
        pagination: true, //分页
        paginationLoop: false,
        showPaginationSwitch: false,
        paginationPreText: '上一页',
        paginationNextText: '下一页',
        responseHandler: function (res) {
            return {
                "rows": res.content,
                "total": res.totalElements
            };
        },
        columns: [
            {field: 'code', title: '单据号', width: '100px', align: 'center',},
            {field: 'time', title: '日期', width: '100px', align: 'center',},
            {field: 'type', title: '单据类型', width: '100px', align: 'center',},
            {field: 'abstractName', title: '摘要', align: 'center',},
            {field: 'borrow', title: '借方', width: '130px', align: 'right',},
            {field: 'loan', title: '贷方', width: '130px', align: 'right',},
            {field: 'endBalance', title: '余额', width: '130px', align: 'right',},
           ],
        onPreBody: function (data) {
            console.log(data); // 1
            if (data.length > 0){
                // console.log(data);
                var balance = accAdd(insertRow.endBalance, 0);
                var insertRowBalance = accAdd(data[0].endBalance, balance);
                for (var i in data) {
                    if (i == 0){
                        balance = balance + data[i].endBalance;
                    }
                    balance = balance + data[i].borrow - data[i].loan;
                    data[i].endBalance = balance;
                }
                //如果是第一页,要在行首加一条数据
                if (this.pageNumber == 1) {
                    newRow = $.extend(true, insertRow.type, insertRow);
                    newRow.endBalance = insertRowBalance;
                    data.unshift(newRow);
                }
            }
        }
    });
}

在onProBody()方法中使用console.log()方法打印

图片

会打印两次data,data是一个列表

第一次打印一个空列表

第二次打印从后端返回的数据

然后下面的操作data时,由于data为空,会报data[0].endBalance不存在的错

解决办法:

添加判断

    if (data.length > 0){
        //body
    }

自己服务器的地址:http://www.zhangnlei.cn/article/16

推荐阅读