为datagrid、treegrid增加右键表头菜单,用于显示或隐藏列,注意:冻结列不在此菜单中
1 var createGridHeaderContextMenu = function(e, field) { 2 e.preventDefault(); 3 var grid = $(this);/* grid本身 */ 4 var headerContextMenu = this.headerContextMenu;/* grid上的列头菜单对象 */ 5 if (!headerContextMenu) { 6 var tmenu = $('<div style="width:100px;"></div>').appendTo('body'); 7 var fields = grid.datagrid('getColumnFields'); 8 console.log('id='+grid.attr('id')); 9 storage=$.localStorage;if(!storage)storage=$.cookieStorage; 10 var cols = storage.get(grid.attr('id')+'hiddenColumns'); 11 var init=true; 12 if(cols){ 13 init=false; 14 } 15 for ( var i = 0; i < fields.length; i++) { 16 var fildOption = grid.datagrid('getColumnOption', fields[i]); 17 console.log(fields[i]+'='+fildOption.hidden); 18 if (!fildOption.hidden||fildOption.hidden==false) { 19 $('<div iconCls="icon-ok" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu); 20 } else { 21 if(init==false){ 22 for(var j=0;j<cols.length;j++){ 23 if(cols[j].field==fields[i]&&cols[j].visible!=false){ 24 //console.log(cols[j].field+'=='+cols[j].visible); 25 $('<div iconCls="icon-empty" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu); 26 } 27 } 28 } 29 } 30 } 31 headerContextMenu = this.headerContextMenu = tmenu.menu({ 32 onClick : function(item) { 33 var field = $(item.target).attr('field'); 34 if (item.iconCls == 'icon-ok') { 35 grid.datagrid('hideColumn', field); 36 $(this).menu('setIcon', { 37 target : item.target, 38 iconCls : 'icon-empty' 39 }); 40 } else if (item.iconCls == 'icon-empty') { 41 grid.datagrid('showColumn', field); 42 $(this).menu('setIcon', { 43 target : item.target, 44 iconCls : 'icon-ok' 45 }); 46 }else{ 47 //恢复表头 48 49 } 50 } 51 }); 52 } 53 headerContextMenu.menu('show', { 54 left : e.pageX, 55 top : e.pageY 56 }); 57 }; 58 59 //$.fn.datagrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu; //屏蔽掉dagagrid表头右键隐藏列的功能 60 $.fn.treegrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu;