bootstrap table新增編輯行時上一行填寫的資料被清空【已解決】
使用bootstrap-table insertRow新增一可編輯行,填入資料後,點選新增下一行時,發現上一行資料被清空了:
檢視bootstrap-table 原始碼:
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 中始終是當時 insertRow 時 params 的資料,在新增行編輯的資料根本未同步到 this.options.data 中,所以在下一次觸發 insertRow 時,會將上一新增行初始化為編輯前的狀態,因此需要解決的問題是:在下一次觸發 insertRow 時,將我們頁面編輯的資料同步到 this.options.data .
檢視bootstrapTable文件:
發現 updateRow 方法傳入引數也是 params,insert 是插入新行,update是更新指定行(~~新增行肯定可以),檢視原始碼:
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 的資料來源,主要的工作就是獲取上一次新增行的索引和編輯後的資料。
//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); }
效果如下: