欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flexgrid扩展

程序员文章站 2022-06-16 17:33:04
...

最近做grid展示。用到了flexgrid,在网上搜索了一番。在加上自己的修改。最终出来了自己的东西。先上图,再贴代码吧


flexgrid扩展
            
    
    博客分类: javascript  

<br>
<table border="0" style="width:95%" cellspacing="0" cellpadding="3" class="small" align="center">
  <tr>
    <td class="Big" ><span class="big3"><img src="/eform/resource/images/menu/big/wf_mine.png" width="32"> 用户列表</span>
    姓名<input id="nickName" type="text" name="nickName" size="15">&nbsp;
    邮箱<input id="userEmail" type="text" name="userEmail" size="15">&nbsp; 
    用户名 <input id="userName" type="text" name="userName" size="15">&nbsp; 
    <input type="button" id="btnQuery" name="btnQuery" value="查询用户">&nbsp;
    <input type="button" id="btnAdd" name="btnAdd" value="添加用户">&nbsp;
    <input type="button" id="btnDelete" name="btnDelete" value="删除用户">&nbsp;
    <input type="button" id="btnEdit" name="btnEdit" value="修改用户">&nbsp;
    <input type="button" id="btnView" name="btnView" value="查看用户">&nbsp;
    <input type="button" id="btnUnlock" name="btnUnlock" value="解锁用户">&nbsp;
    <input type="button" id="btnLock" name="btnLock" value="锁定用户">&nbsp;
    <input type="button" id="btnExport" name="btnExport" value="导出用户">&nbsp;
    <input type="button" id="btnImport" name="btnImport" value="导入用户">&nbsp;
    <input type="button" id="btnTemplate" name="btnTemplate" value="下载模板 ">&nbsp;
    </td>  
   </tr> 
</table>
<br>
<form id="listDataForm" name="listDataForm" action="/eform/system/user/index.xos" method="post"> 
<table id="tablelistdata" style="width:95%" class="TableList" align="center"> 
	<thead>
		<tr class="TableHeader" id="bodydataheader">  
			<td width="15" axis="-1" class="TableCorner"><input id="chkallselect" type="checkbox" name="chkallselect" class="noborder" ></td> 
			<td width="30%" axis="0" class="TableCorner" id="userName_0" onclick="sortFunction('userName','asc');">用户名 </td>
			<td width="15%" axis="1" class="TableCorner" id="nickName_0" onclick="sortFunction('nickName','asc');">姓名</td>
			<td width="50%" axis="2" class="TableCorner" id="userEmail_0" onclick="sortFunction('userEmail','asc');">邮箱</td> 
			<td width="5%" axis="3" class="TableCorner">锁定</td> 
		</tr>
	</thead>
	 
	<tbody id="bodylistdata">
		
		<tr class="TableLine1 "> 
			<td width="15"><input id="chk_402880933f5fc093013f5fc09d95044b" class="itemchk noborder" type="checkbox" value="402880933f5fc093013f5fc09d95044b"></td>  
			<td align="left"  >carl.song</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
		<tr class="TableLine1 TableRowHover"> 
			<td width="15"><input id="chk_4028809340d4a9860140d4ab21910001" class="itemchk noborder" type="checkbox" value="4028809340d4a9860140d4ab21910001"></td>  
			<td align="left"  >sysadmin</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
		<tr class="TableLine1 "> 
			<td width="15"><input id="chk_40288093412fcc5a01412fccfa040002" class="itemchk noborder" type="checkbox" value="40288093412fcc5a01412fccfa040002"></td>  
			<td align="left"  >carl.liu</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
		<tr class="TableLine1 TableRowHover"> 
			<td width="15"><input id="chk_40288093412fd12d01412fd2e6300002" class="itemchk noborder" type="checkbox" value="40288093412fd12d01412fd2e6300002"></td>  
			<td align="left"  >carl.wang</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
		<tr class="TableLine1 "> 
			<td width="15"><input id="chk_40288093412fda4501412fdb20970001" class="itemchk noborder" type="checkbox" value="40288093412fda4501412fdb20970001"></td>  
			<td align="left"  >carl.ye</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
		<tr class="TableLine1 TableRowHover"> 
			<td width="15"><input id="chk_40288093412fda4501412fdd73070002" class="itemchk noborder" type="checkbox" value="40288093412fda4501412fdd73070002"></td>  
			<td align="left"  >kevin.ye</td>
			<td align="left" > </td>
			<td align="left" > </td> 
			<td align="left" >否</td> 
		</tr>
		
	</tbody>
	<tfoot id="footlistdata">
		 <tr class="TableFooter">
		 	<td align="left"  colspan="5" id="pagemessage">  
		 	</td>
		 </tr>
	</tfoot>
	
	
</table>  
</form>

 

function sortFunction(asortid,asortorder){
	//jQuery("#"+asortid).empty();
	jQuery("#userName_0").attr("onclick","sortFunction('userName','asc')");
	jQuery("#userName_0").html("用户名 ");
	jQuery("#nickName_0").attr("onclick","sortFunction('nickName','asc')");
	jQuery("#nickName_0").html("姓名");
	jQuery("#userEmail_0").attr("onclick","sortFunction('userEmail','asc')");
	jQuery("#userEmail_0").html("邮箱");
	if(asortorder=='asc'){  
		jQuery("#"+asortid+"_0").attr("onclick","sortFunction('"+asortid+"','desc')");
		jQuery("#"+asortid+"_0").html(jQuery("#"+asortid+"_0").html()+'&nbsp;<img src="/eform/resource/themes/10/images/ddn.png">');
	} 
	else{ 
		jQuery("#"+asortid+"_0").attr("onclick","sortFunction('"+asortid+"','asc')");
		jQuery("#"+asortid+"_0").html(jQuery("#"+asortid+"_0").html()+'&nbsp;<img src="/eform/resource/themes/10/images/uup.png">');
	} 
	jQuery("#pagemessage").flexOptions({sortname:  asortid,sortorder:asortorder});
	jQuery("#pagemessage").flexReload();
} 
function exportFunction(){
	var iform=_$("listDataForm");
	iform.action="/eform/system/user/exportdata.xos"; 
	iform.submit();
}
var  urlWindowGroup=null;
function closeWindow(){
	if(urlWindowGroup!=null){
		urlWindowGroup.close();
		window.location='/eform/system/user/index.xos';
	}
}
function importFunction(){
	urlWindowGroup=
		new UI.URLWindow({
	        width: 400, 
	        maxWidth:400,
	        height: 200,
	        maxHeight:200, 
	        id:'importUserData', 
	        shadow: true,
	        theme: "mac_os_x",
	        url: '/eform/system/user/excel.xos'});
	    
		urlWindowGroup.center().show().activate();  
}
function downFunction(){
	var iform=_$("listDataForm");
	iform.action="/eform/system/user/down.xos"; 
	iform.submit();
}
jQuery(function() {
			jQuery(":button").button(); 
			jQuery(":text").textbox(); 
			jQuery("#btnQuery").click(function(){queryFunction();}); 
			jQuery("#btnAdd").click(function(){newFunction();});
			jQuery("#btnDelete").click(function(){deleteFunction();});
			jQuery("#btnEdit").click(function(){editFunction();});
			jQuery("#btnView").click(function(){viewFunction();});
			jQuery("#btnUnlock").click(function(){unlockFunction();});
			jQuery("#btnLock").click(function(){lockFunction();}); 
			jQuery("#btnExport").click(function(){exportFunction();});
			jQuery("#btnImport").click(function(){importFunction();});
			jQuery("#btnTemplate").click(function(){downFunction();});
			jQuery("#chkallselect").change(function(){ 
				var ickeck=this.checked;
				jQuery("input.itemchk").each(function(j){ 
					this.checked=ickeck; 
				});
			});
			var maiheight = document.documentElement.clientHeight; 
			var otherpm = 150; //GridHead,toolbar,footer,gridmargin
			var gh = maiheight - otherpm;
			var option = {
					height : gh, //flexigrid插件的高度,单位为px
					total:6,
					page:1,
					pages:1,
					rp:20,
					url: '/eform/system/user/ajax.xos',
					path:'/eform/',
					dataType: 'json',
					width:'97%',
					usepager:true,
					errormsg  : '连接错误', 
					pagetext  : '页',
					pagestat  : '显示记录从{from}到{to},总数 {total} 条',
					outof     : '的',
					findtext  : '查询',
					firsttext : '第一页',
					prevtext  : '前一页',
					nexttext  : '下一页',
					lasttext  : '最后页',
					refresh   : '刷新',
					procmsg   : '正在处理数据,请稍候 ...',
					nomsg     : '没有数据需要显示',
					alertTitle: '系统提示',
					cleartitle: '清空',
					colModel : [{ 
						name : 'userName' 
					},{ 
						name : 'nickName' 
					},{ 
						name : 'userEmail' 
					},{ 
						name : 'islock' 
					}],
					buttons: [], 
		            searchitems: [	{ id:'nickName', name: 'nickName'},
								    { id:'userEmail', name: 'userEmail'},
								    { id:'userName', name: 'userName' }
								    ], 
					coldata:'bodylistdata',headerdata:'bodydataheader',
					autoload: false, //自动加载,即第一次发起ajax请求
					hideOnSubmit: true //是否在回调时显示遮盖 
			};
			jQuery("#pagemessage").flexigrid(option);
		});	 
		function queryFunction(){
			jQuery("#pagemessage").flexReload();
		}
		

 主体flexgrid代码:

/*
 * Flexigrid for jQuery -  v1.1
 *
 * Copyright (c) 2008 Paulo P. Marinas (code.google.com/p/flexigrid/)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 */
(function ($) {
	/*
	 * jQuery 1.9 support. browser object has been removed in 1.9 
	 */
	var browser = $.browser;
	
	if (!browser) {
		function uaMatch( ua ) {
			ua = ua.toLowerCase();

			var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
				/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
				/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
				/(msie) ([\w.]+)/.exec( ua ) ||
				ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
				[];

			return {
				browser: match[ 1 ] || "",
				version: match[ 2 ] || "0"
			};
		};

		var matched = uaMatch( navigator.userAgent );
		browser = {};

		if ( matched.browser ) {
			browser[ matched.browser ] = true;
			browser.version = matched.version;
		}

		// Chrome is Webkit, but Webkit is also Safari.
		if ( browser.chrome ) {
			browser.webkit = true;
		} else if ( browser.webkit ) {
			browser.safari = true;
		}
	}
	
    /*!
     * START code from jQuery UI
     *
     * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
     * Dual licensed under the MIT or GPL Version 2 licenses.
     * http://jquery.org/license
     *
     * http://docs.jquery.com/UI
     */
     
    if(typeof $.support.selectstart != 'function') {
        $.support.selectstart = "onselectstart" in document.createElement("div");
    }
    
    if(typeof $.fn.disableSelection != 'function') {
        $.fn.disableSelection = function() {
            return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
                ".ui-disableSelection", function( event ) {
                event.preventDefault();
            });
        };
    }
    
    /* END code from jQuery UI */
    
	$.addFlex = function (t, p) {
		if (t.grid) return false; //return if already exist
		p = $.extend({ //apply default properties
			height: 200, //default height//flexigrid插件的高度,单位为px
			width: 'auto', //auto width//宽度值,auto表示根据每列的宽度自动计算
			striped: true, //apply odd even stripes//是否显示斑纹效果,默认是奇偶交互的形式
			novstripe: false,
			minwidth: 30, //min width of columns//列的最小宽度
			minheight: 20, //min height of columns//列的最小高度
			resizable: false, //allow table resizing//resizable table是否可伸缩
			url: false, //URL if using data from AJAX//ajax url,ajax方式对应的url地址
			method: 'POST', //data sending method// data sending method,数据发送方式
			dataType: 'json', //type of data for AJAX, either xml or json// type of data loaded,数据加载的类型,xml,json
			errormsg: 'Connection Error',//错误提升信息
			cleartitle:'clear',
			usepager: false,//是否分页
			nowrap: true,//是否不换行
			page: 1, //current page 默认当前页
			total: 1, //total pages 总页面数
			useRp: false, //use the results per page select box 是否可以动态设置每页显示的结果数
			rp: 25, //results per page 每页默认的结果数
			rpOptions: [10,15, 25, 30], //allowed per-page values //可选择设定的每页结果数
			title: false,//是否包含标题 
			pagestat: 'Displaying {from} to {to} of {total} items',//显示当前页和总页面的样式
			pagetext: 'Page',
			outof: 'of',
			findtext: 'Find',
			firsttext:'',
			prevtext:'',
			nexttext:'',
			lasttext:'',
			coldata:'bodylistdata',
			headerdata:'bodydataheader',
			params: [], //allow optional parameters to be passed around
			searchitems:[],
			procmsg: 'Processing, please wait ...',//正在处理的提示信息
			query: '',//搜索查询的条件
			qtype: '',//搜索查询的类别
			qop: "Eq", //搜索的操作符
			nomsg: 'No items',//无结果的提示信息
			minColToggle: 1, //minimum allowed column to be hidden
			showToggleBtn: true, //show or hide column toggle popup
			hideOnSubmit: true,//显示遮盖
			autoload: true,//自动加载
			blockOpacity: 0.5,//透明度设置
			preProcess: false,
			addTitleToCell: false, // add a title attr to cells with truncated contents
			dblClickResize: false, //auto resize column by double clicking
			onDragCol: false,//拖拽列事件
			onToggleCol: false,//合并列事件
			onChangeSort: false,//改变排序
			onDoubleClick: false,//双击事件
			onSuccess: false,
			onError: false,
			onSubmit: false, //using a custom populate function
			showcheckbox: false,//是否显示checkbox
			rowhandler: false, //是否启用行的扩展事情功能
			path:'',
			rowbinddata: false, 
			alertTitle:'System Message',
            __mw: { //extendable middleware function holding object
                datacol: function(p, col, val) { //middleware for formatting data columns
                    var _col = (typeof p.datacol[col] == 'function') ? p.datacol[col](val) : val; //format column using function
                    if(typeof p.datacol['*'] == 'function') { //if wildcard function exists
                        return p.datacol['*'](_col); //run wildcard function
                    } else {
                        return _col; //return column without wildcard
                    }
                }
            },
            getGridClass: function(g) { //get the grid class, always returns g
                return g;
            },
            gridClass: "flexigrid",
            datacol: {}, //datacol middleware object 'colkey': function(colval) {}
            colResize: true, //from: http://*.com/a/10615589
            colMove: true,
            onrowchecked: false
		}, p);
		$(t).show() //show if hidden
			.attr({
				cellPadding: 0,
				cellSpacing: 0,
				border: 0
			}) //remove padding and spacing
			.removeAttr('width'); //remove width properties
		//create grid class
		var g=null ;
		g= {  
			hideLoading: function() {
                $('.pReload', t).removeClass('loading');
//                if (p.hideOnSubmit) $(g.block).remove();
                $('.pPageStat', t).html(p.errormsg);
                this.loading = false;
            },
			addData: function (data) { //parse data
				if (p.dataType == 'json') {
					data = $.extend({rows: [], page: 0, total: 0}, data);
				} 
				if (p.preProcess) {
					data = p.preProcess(data);
				} 
				if (p.usepager) {
					$('.pReload', t).removeClass('loading');
				}
				this.loading = false;
				if (!data) {
					if (p.usepager) $('.pPageStat', t).html(p.errormsg);
                    if (p.onSuccess) p.onSuccess(this);
					return false;
				} 
				
				p.total = data.total; 
				if (p.total === 0) {
					$('#bodylistdata').empty(); 
					$('#bodylistdata').html('<tr class="TableLine1"><td align="left" colspan="'+(p.colModel.length+1)+'">'+p.nomsg+'</td></tr>');
					//$(t).empty();
					p.pages = 0;
					p.page = 0;
					this.buildpager(); 
                    if (p.onSuccess) p.onSuccess(this);
//                    if (p.hideOnSubmit) {
//    					$(g.block).remove();
//    				}
                    $('#chkallselect').prop("disabled", true);
					return false;
				}
				p.pages = Math.ceil(p.total / p.rp); 
				p.page = data.page; 
				if (p.usepager)this.buildpager();
				//build new body 
				
				var ths = $('#'+p.headerdata+' td'); 
                var tbhtml = [];
//                tbhtml.push("<tbody>"); 
				if(data.error&&data.error!=''){
					$.messageBox.alert({title:p.alertTitle,content:data.error,type:'error'});
					return false;
				} 
				$.each(data.rows, function (i, row) { 
					tbhtml.push("<tr ");  
					tbhtml.push("id=\"row",row.id,"\" "); 
					if (row.name) tbhtml.push(" name=\"",row.name,"\" ");
					if (row.color) {
						tbhtml.push(" style=\" background:",row.color,"\" "); 
					} else {
						if (i % 2==0)
							tbhtml.push(" class=\"TableLine1 TableRowHover\" "); 
						else
							tbhtml.push(" class=\"TableLine1\" "); 
					} 
//					if (p.rowbinddata) {
//                        tbhtml.push(" ch=\"", row.cell.join("_FG$SP_"), "\" ");
//                    }
					tbhtml.push(">");
					var trid = row.id;
					
					$(ths).each( //add cell
						function (j) {  
                            tbhtml.push("<td "); 
                            
							var idx = $(this).attr('axis');  
                            var div = []; 
                            if (idx == "-1") {  
                                div.push("<input type=\"checkbox\" id=\"chk_", row.id, "\" class=\"itemchk\" value=\"", row.id, "\"/>");
	                        }else {
	                        	var divInner=null;  
								// If the json elements aren't named (which is typical), use numeric order 
                                if (typeof row.cell[idx] != "undefined") {
                                	divInner = (row.cell[idx] !== null) ? row.cell[idx] : '&nbsp;'; //null-check for Opera-browser
                                } else {
                                	divInner = row.cell[p.colModel[idx].name];
                                }
                                divInner = p.__mw.datacol(p, $(this).attr('abbr'), divInner); //use middleware datacol to format cols 
                                if (this.process) {
                                    divInner = this.process(divInner, trid);
                                }  
                                
                                div.push(divInner);
                            }  
//                            tbhtml.push(" abbr=\"",$(this).attr('abbr'),"\" ");
                            tbhtml.push(">", div.join(""), "</td>"); 
						});
						tbhtml.push("</tr>");
				}); 
 
				$("#"+p.coldata).empty(); 
//				alert(tbhtml.join(""));
                $("#"+p.coldata).html(tbhtml.join(""));
                tbhtml=null;
				this.addCellProp();
				this.addRowProp(); 
//				tbody = null;
				data = null;
				i = null;
				$('#chkallselect').prop("disabled", false);
				if (p.onSuccess) {
					p.onSuccess(this);
				}
//				if (p.hideOnSubmit) {
//					$(g.block).remove();
//				} 
				if (browser.opera) {
					$(t).css('visibility', 'visible');
				}
			}, 
			buildpager: function () { //rebuild pager based on new properties
				if(p.page==0&&p.pages==0&&p.total==0){
					$('#_input', t).val(1);
					$('.pcontrol span', t).html(1);
					$('.pPageStat', t).html(p.nomsg); 
				}else{
					$(':input', t).val(p.newp);
					$('.pcontrol span', t).html(p.pages);
					var r1 = (p.page - 1) * p.rp + 1;
					var r2 = r1 + p.rp - 1;
					if (p.total < r2) {
						r2 = p.total;
					}
					var stat = p.pagestat;
					stat = stat.replace(/{from}/, r1);
					stat = stat.replace(/{to}/, r2);
					stat = stat.replace(/{total}/, p.total);
					$('.pPageStat', t).html(stat);
//					$('#chkallselect').prop("disabled", false);
				}
				
			},
			populate: function () { //get latest data 
				if (this.loading) {
					return true;
				} 
				if (p.onSubmit) {
					var gh = p.onSubmit();
					if (!gh) {
						return false;
					}
				} 
				this.loading = true;
				if (!p.url) {
					return false;
				} 
				$('.pPageStat', t).html(p.procmsg); 
				$('.pReload', t).addClass('loading');
//				$(g.block).css({
//					top: t.offsetTop
//				}); 
//				if (p.hideOnSubmit) {
//					$(t).prepend(g.block);
//				} 
				if (browser.opera) {
					$(t).css('visibility', 'hidden');
				}
				
				if (!p.newp) {
					p.newp = 1;
				} 
				if (p.page > p.pages) {
					p.page = p.pages;
				} 
				var param = [{
					name: 'page',
					value: p.newp
				}, {
					name: 'pageSize',
					value: p.rp
				}, {
					name: 'orderBy',
					value: p.sortname
				}, {
					name: 'sortorder',
					value: p.sortorder
				}];  
				if(p.searchitems){//add search condition carl.song 2013-06-19
					var sitems=p.searchitems;
					for(var pi=0;pi<sitems.length;pi++){
						var sitem=sitems[pi];
						var tparams=null;
						
//						tparams.push({name:'",sitem.name,"',value:'");
						var squery =$('#'+sitem.id).val();
						squery=jQuery.trim(squery);
						
						if(squery!=""){ 
							tparams={name:sitem.name,value:squery};
						} 
//						var tparam=tparams.join(" ");
						if(tparams!=null)
						param[param.length]=tparams;
//						tparam=null;
						tparams=null;
					}
				}
//				alert(param.toString());
				$.ajax({
					type: p.method,
					url: p.url,
					data: param,
					dataType: p.dataType,
					success: function (data) { 
//						alert(data);
						g.addData(data);
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						try {
							if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
						} catch (e) {}
					}
				});
			},
			doSearch: function () {
				if(p.searchitems){
					var sitems=p.searchitems;
					for(var i=0;i<sitems.length;i++){
						var sitem=sitems[i];
						var query =$('#'+sitem.id,g.tDiv).val();
						if(sitem.reg){
							if(!sitem.reg.test(query)){
								$.messageBox.alert({title:p.alertTitle,content:sitem.message,type:'error'});
								return ;
							}
						} 
					}
				} 
				p.newp = 1;
				this.populate();
			},
			changePage: function (ctype) { //change page
				if (this.loading) {
					return true;
				}
				switch (ctype) {
					case 'first':
						p.newp = 1;
						break;
					case 'prev':
						if (p.page > 1) {
							p.newp = parseInt(p.page, 10) - 1;
						}
						break;
					case 'next':
						if (p.page < p.pages) {
							p.newp = parseInt(p.page, 10) + 1;
						}
						break;
					case 'last':
						p.newp = p.pages;
						break;
					case 'input':
						var nv = parseInt($('#_input', t).val(), 10);
						if (isNaN(nv)) {
							nv = 1;
						}
						if (nv < 1) {
							nv = 1;
						} else if (nv > p.pages) {
							nv = p.pages;
						}
						$('#_input', t).val(nv);
						p.newp = nv;
						break;
				}
				if (p.newp == p.page) {
					return false;
				}
				if (p.onChangePage) {
					p.onChangePage(p.newp);
				} else {
					this.populate();
				}
			},
			cellProp: function(n, ptr, pth) {
                var tdDiv = document.createElement('div');
                if (pth != null) {
                    if (p.sortname == $(pth).attr('abbr') && p.sortname) {
                        this.className = 'sorted';
                    }
                    $(tdDiv).css({ textAlign: pth.align, width: $('div:first', pth)[0].style.width });
                    if (pth.hide) $(this).css('display', 'none');
                }
                if (p.nowrap == false) $(tdDiv).css('white-space', 'normal');

                if (this.innerHTML == '') this.innerHTML = '&nbsp;';

                //tdDiv.value = this.innerHTML; //store preprocess value
                tdDiv.innerHTML = this.innerHTML;
               // alert(this.innerHTML);
                var prnt = $(this).parent()[0];
                var pid = false;
                if (prnt.id) pid = prnt.id.substr(3);
                if (pth != null) {
                    if (pth.process)
                    { pth.process(tdDiv, pid); }
                } 
                $("input.itemchk", tdDiv).each(function() {
                    $(this).click(function() {
                        if (this.checked) {
                            $(ptr).addClass("trSelected");
                        }
                        else {
                            $(ptr).removeClass("trSelected");
                        }
                        if (p.onrowchecked) {
                            p.onrowchecked.call(this);
                        }
                    });
                });
                $(this).empty().append(tdDiv).removeAttr('width'); //wrap content
//                g.addTitleToCell(tdDiv);
                //add editable event here 'dblclick',如果需要可编辑在这里添加可编辑代码 
            },
			addCellProp: function () {
//				var $gF = this.cellProp;
//				$('tbody tr td',t).each(function () {
//					var id=$(this).children(0).html();
////					alert();
////					alert(id);
//					if(p.showcheckbox&&id.indexOf("itemchk")<=0){
//						var ctd = jQuery('<td/>');
//						var ctdch = jQuery('<input type="checkbox" id="chk_'+$(this).children(0).attr("id")+'" class="itemchk" value="'+$(this).children(0).attr("id")+'"/>');
//						ctdch.addClass("noborder");
//						ctd.addClass("cth").attr({ width: "15"}).append(ctdch);
//						$(this).prepend(ctd);
//					}
//					
////					var n = $('td', $(this).parent()).index(this); 
////					var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
////					var ptr = $(this).parent(); 
////				    $gF.call(this, n, ptr, pth);
//				}); 
//				$gF=null;
				
			},  
			addRowProp: function () {
                $('#'+p.coldata+' tr').each(
                    function() { 
                    	var _this=$(this);
                    	$(this).find("input.itemchk").change(function(e){  
                    		 if (this.checked) {
                    			 _this.addClass("TableRowActive");
                             }else {
                            	 _this.removeClass("TableRowActive");
                             }
                             if (p.onrowchecked) {
                                 p.onrowchecked.call(this);
                             }
                    	});
                    }
                );
				
				if (p.rowhandler) {
                    p.rowhandler(this);
                }
				if (browser.msie && browser.version < 7.0) {
					$(this).hover(function () {
						$(this).addClass('TableRowActive');
					}, function () {
						$(this).removeClass('TableRowActive');
					});
				}
			},
			checkAllOrNot: function(parent) {
                var ischeck = this.checked; 
                $("input.itemchk", t).each(function() {
                    this.checked = ischeck;
                   var $tr= $(this).parent().parent();
                   $tr.toggleClass("trSelected",ischeck); 
                    //Raise Event
                    if (p.onrowchecked) {
                        p.onrowchecked.call(this);
                    }
                });
            }, 
			pager: 0
		};
         
		g = p.getGridClass(g); //get the grid class

//		alert(p.usepager);
		//add td & row properties  
		if ((p.url == false || p.url == "")) {
			g.addCellProp();
			g.addRowProp();
		}else if(p.autoload==false){
			g.addCellProp();
			g.addRowProp();
		} 
		
		// add pager
		if (p.usepager) {  
			var html='<div class="pFirst pButton" style="cursor:pointer;" title="'+p.firsttext+'" ><img src="'+p.path+'/resource/images/pages/page-first.png"></div>';
			html=html+'<div class="pPrev pButton" style="cursor:pointer;" title="'+p.prevtext+'"><img src="'+p.path+'/resource/images/pages/page-prev.png"></div>';
			
			html=html+' <div class="btnseparator"></div><div class="pButton"> <span class="pcontrol">'; 
			html=html+ p.pagetext+'<input type="text" id="_input" name="_input" class="BigInput ui-corner-all" size="4" value="1" /> ' + p.pagetext+ ' '+ p.outof+'<span> 1 </span></span></div>';
			html=html+'<div class="btnseparator"></div> ';
			html=html+'<div class="pNext pButton" style="cursor:pointer;" title="'+p.nexttext+'"><img src="'+p.path+'/resource/images/pages/page-next.png"></div>';
			html=html+'<div class="pLast pButton" style="cursor:pointer;" title="'+p.lasttext+'"><img src="'+p.path+'/resource/images/pages/page-last.png"></div>';
			
			html=html+' <div class="btnseparator"></div> '; 
			html=html+' <div class="pReload pButton" style="cursor:pointer;"  title="'+p.refresh+'"><img src="'+p.path+'/resource/images/pages/refresh.png"></div> '; 
			html=html+' <div class="btnseparator"></div> '; 
			html=html+' <div class="pButton"><span class="pPageStat"></span></div> ';   
			$(t).append(html);
			$('.pReload',t).click(function () {
				g.populate();
			});
			$('.pFirst', t).click(function () {
				g.changePage('first');
			});
			$('.pPrev', t).click(function () {
				g.changePage('prev');
			});
			$('.pNext', t).click(function () {
				g.changePage('next');
			});
			$('.pLast', t).click(function () {
				g.changePage('last');
			});
			$('.pcontrol input', t).keydown(function (e) {
				if (e.keyCode == 13) { 
                    g.changePage('input');
				}
			}).change(function () {
				g.changePage('input');
			});
			if (browser.msie && browser.version < 7) $('.pButton', t).hover(function () {
				$(this).addClass('pBtnOver');
			}, function () {
				$(this).removeClass('pBtnOver');
			}); 
			g.buildpager();
		}
		$(g.pDiv).append("<div style=\"clear:both\"></div>"); 
		
		
		//make grid functions accessible
		t.p = p;
		t.grid = g;
		
		// load data
		if (p.url && p.autoload) {
			g.populate();
		}
		return t;
	};
	
	var docloaded = false;
	$(document).ready(function () {
		docloaded = true;
	});
	$.fn.flexigrid = function (p) {
		return this.each(function () {
			if (!docloaded) {
				$(this).hide();
				var t = this;
				$(document).ready(function () {
					$.addFlex(t, p);
				});
			} else {
				$.addFlex(this, p);
			}
		});
	}; //end flexigrid
	$.fn.flexReload = function (p) { // function to reload grid
		return this.each(function () {
			if (this.grid && this.p.url) this.grid.populate();
		});
	}; //end flexReload  
    $.fn.ChangePage = function(type) {
        return this.each(function() {
            if (this.grid) {
                this.grid.changePage(type);
            }
        });
    };
	$.fn.flexOptions = function (p) { //function to update general options
		return this.each(function () {
			if (this.grid) $.extend(this.p, p);
		});
	}; //end flexOptions
	$.fn.GetOptions = function() {
        if (this[0].grid) {
            return this[0].p;
        }
        return null;
    };  
	$.fn.flexAddData = function (data) { // function to add data to grid
		return this.each(function () {
			if (this.grid) this.grid.addData(data);
		});
	}; 
})(jQuery);

 

  • flexgrid扩展
            
    
    博客分类: javascript  
  • 大小: 27 KB