bootstrap table新增编辑行时上一行填写的数据被清空

 

使用bootstrap-table insertRow新增一可编辑行,填入数据后,点击新增下一行时,发现上一行数据被清空了:bootstrap

查看bootstrap-table 源码:this

BootstrapTable.prototype.insertRow = function (params) {
        if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
            return;
        }
        this.options.data.splice(params.index, 0, params.row);
        this.initSearch();
        this.initPagination();
        this.initSort();
        this.initBody(true);
    };

其中 params 是咱们前台使用 $('#tSableId').bootstrap('insertRow',{index:rowIndex,row:rowObj}); 传入的新增行JSON格式数据对象,新增行的数据会存放在 this.options.data 中,而后调用 this.initSearch(); 从新查一遍  this.options.data 中的数据。spa

如上图,每次新增行时,上一次新增的数据在 this.options.data 中始终是当时 insertRowparams 的数据,在新增行编辑的数据根本未同步到 this.options.data 中,因此在下一次触发 insertRow 时,会将上一新增行初始化为编辑前的状态,所以须要解决的问题是:在下一次触发 insertRow 时,将咱们页面编辑的数据同步到 this.options.data .
prototype

查看bootstrapTable文档:3d

发现 updateRow 方法传入参数也是 params,insert 是插入新行,update是更新指定行(~~新增行确定能够),查看源码:code

BootstrapTable.prototype.updateRow = function (params) {
        var that = this;
        var allParams = $.isArray(params) ? params : [ params ];

        $.each(allParams, function(i, params) {
            if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
                return;
            }
            $.extend(that.options.data[params.index], params.row);
        });

        this.initSearch();
        this.initPagination();
        this.initSort();
        this.initBody(true);
    };

其中  $.extend(that.options.data[params.index], params.row);  就是将 this.options.data 中指定行 index 数据同步更新。对象

所以,解决方案就是:在下一次新增行前,先将上一次新增行的数据经过 updateRow 方法同步到当前页 bootstrap table 的数据源,主要的工做就是获取上一次新增行的索引和编辑后的数据。blog

//addIndex表示当前新增行索引
            //rowIndex表示表格原有索引
            if( addIndex!=rowIndex ) {
                var dataIndex = addIndex -1;
                var columns = $('#listTable tr[data-index="'+dataIndex+'"] td.editable');
                var obj = new Object();
                for (var i=0; i<columns.length; i++) {
                    var td = $(columns[i]).find('input');
                    var key = colStr[i];
                    obj[key] = td.val();

                }
                var params = {index:(addIndex-1),row:obj};
                listTab.bootstrapTable("updateRow",params);
            }

 效果以下:索引