easyui中根據后台數據動態改變datagrid的列


最近在做系統的時候需要根據后台提供的數據改變datagrid的列的field和 title,效果如下:

在點擊下拉框改變年份的時候動態改變列

js 代碼如下

//獲取選擇的月份
$('#Year_Combobox').combobox({
value:nowYear, //當前年份
panelHeight:true,
onSelect:function(record){
$.getJSON('interface/asynRead.php?cmd=getColumns',{
year:record.value
},function(data){
if(data.ret=='OK'){
columns1.length=0;  //清空列的數組
columns2.length=0; //清空列的數組
var arr=data.rows;
$.each(arr, function(i,item){
var year=item.YMonth;
columns1.push({
"field": year+'',  // 要求這里必須是 year+‘’ 將year轉化為字符串
"title": year+'',  //同理
"halign": 'center' ,
"colspan":3
});
columns2.push({
field: 'a'+year,
title: year,
width: 150,
align: 'right',
halign: 'center',
formatter: function(v, r, i) {
if(typeof v == 'undefined') {
return '-';
} else {
return "<a href='#' onclick='checkNum("+year+"," + r.checkNum + ");'>" + v + "</a>";
}
}
},{
field: 'a'+year+'Num',
title: year+'筆數',
width: 100,
align: 'right',
halign: 'center',
formatter: function(v, r, i) {
if(typeof v == 'undefined') {
return '-';
} else {
return v;
}
}
},{
field: 'a'+year+'check',
title: '核對',
width: 30,
align: 'right',
halign: 'center',
formatter: function(v, r, i) {
if(v == 0) {
return "<img src='img/no2.png'/>";
} else if(v == 1) {
return "<img src='img/yes.png'/>";
} else if(v == 2) {
return "<img src='img/quan.png'/>";
} else {
return '-';
}
}
});
});
$('#Sdatagrid').datagrid('loadData', {
rows: [],
ret: "OK"
});
$('#Sdatagrid').datagrid({
columns:[columns1,columns2],
url:''
});

}});

}});

 

html 代碼:

<div class="f14 w pr bgWhite p-5" id="Ssearch" >
    <label  >年份:</label>
    <select id="Year_Combobox" >
   <option value="2021">2021</option>
   <option value="2020">2020</option>
   <option value="2019">2019</option>
   <option value="2018">2018</option>
   <option value="2017">2017</option>
   </select>
   <a href='#' id='Slink_button' class='easyui-linkbutton fb f16 ml-25' data-options="iconCls:'icon-search'" >查詢</a>
</div>
<table id="Sdatagrid"></table>

 

需要注意兩點:

1. feild 是 year+'' 把year轉化為字符串

2. 在selelct 年份切換的時候 datagrid會自動加載,從而出錯,需要設置 datagrid的url 為空,在點擊查詢的時候再給datagrid賦上url屬性 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM