引言
最近公司的項目中使用到jqGrid控件,官方演示程序中grid的列都是固定的。
<script id="defined grid" type="text/javascript"> sProgID = "VDQ009" var grdMast = clone(oMagicGrid); grdMast.GridID = 'grid1'; grdMast.width = 980; grdMast.height = 300; grdMast.Fun = 'Mast'; grdMast.pager = 'grid1Pager'; grdMast.btnadd = false; grdMast.sortable = true; grdMast.loadonce = true; grdMast.colNames = ['操作', '期別', '廠商編號', '廠商簡稱', '評分類別代碼','可改變的列...','得分']; grdMast.colModel = [{ name: 'acts', width: 45, fixed: true, sortable: false, resize: false }, { name: 'AccPeriod', index: 'AccPeriod', width: 60 }, { name: 'VendorID', index: 'VendorID', width: 80 }, { name: 'AbbrName', index: 'AbbrName', width: 100 }, { name: 'ScoreType', index: 'ScoreType', width: 80 }, { name: 'changingColumn', index: 'changingColumn', width: 80 }, { name: 'Score', index: 'Score', width: 80 } ]; grdMast.FrmQuery = 'frmQuery'; grdMast.hideCol = ['acts']; </script>
問題
項目中有一個功能是:根據不同的篩選條件,調用同一個存儲過程,但存儲過程返回的結果的列數是不同的,可能有少到6列,多到20列的字段呈現。
這樣jqGrid固定列的模式就滿足不了需求。而jqGrid的colNames、colModel都是不可更改的。
解決方案
這里通過 重新加載grid 的辦法,對colNames、colModel重新賦值,就可以實現動態列的顯示了。
關鍵在於重新加載grid之前,需要調用 GridUnload() 這樣一個方法,下面給出部分代碼片段:
jQuery("#grid1").GridUnload(); //destroy the grid.see this website:http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods switch (sType) { case "VDQ02020": grdMast.colNames = ['操作', '期別', '廠商編號', '廠商簡稱', '評分類別代碼', '001', '002', '003', '004', '分數']; grdMast.colModel = [{ name: 'acts', width: 45, fixed: true, sortable: false, resize: false }, { name: 'AccPeriod', index: 'AccPeriod', width: 60 }, { name: 'VendorID', index: 'VendorID', width: 80 }, { name: 'AbbrName', index: 'AbbrName', width: 100 }, { name: 'ScoreType', index: 'ScoreType', width: 80 }, { name: 'A', index: 'A', width: 80 }, { name: 'B', index: 'B', width: 80 }, { name: 'C', index: 'C', width: 80 }, { name: 'D', index: 'D', width: 80 }, { name: 'END', index: 'END', width: 80 } ]; break; case "VDQ02021": grdMast.colNames = ['操作', '期別', '廠商編號', '廠商簡稱', '評分類別代碼', '交期得分']; grdMast.colModel = [{ name: 'acts', width: 45, fixed: true, sortable: false, resize: false }, { name: 'AccPeriod', index: 'AccPeriod', width: 60 }, { name: 'VendorID', index: 'VendorID', width: 80 }, { name: 'AbbrName', index: 'AbbrName', width: 100 }, { name: 'ScoreType', index: 'ScoreType', width: 80 }, { name: 'DUEScore', index: 'DUEScore', width: 80 } ]; break;
然后再對grid進行加載,就可以實現項目的功能要求了。
希望本文對你有幫助。