自己写的一个Ext.grid.EditorGridPanel示例

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>可编辑的表格</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<style type="text/css">
				.x-grid-record-red table{   
				    color: #FF0000;   
				}
				.allow-float {clear:none!important;} /* 允许该元素浮动 */  
				.all-field {
			        float:left;
			        padding:0 0 0 10px;
		    	}
		</style>
		<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />
		<script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script>
		<script type="text/javascript" src="extjs/ext-all.js"></script>
		<script type="text/javascript" src="extjs/locale/ext-lang-zh_CN.js"></script>
		<script>
		/****begin****/
Ext.grid.CheckColumn = function(config) {
	Ext.apply(this, config);
	if (!this.id) {
		this.id = Ext.id();
	}
	this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype = {
	init : function(grid) {
		this.grid = grid;
		this.grid.on('render', function() {
			var view = this.grid.getView();
			view.mainBody.on('mousedown', this.onMouseDown, this);
		}, this);
	},

	onMouseDown : function(e, t) {
		if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
			e.stopEvent();
			var index = this.grid.getView().findRowIndex(t);
			var record = this.grid.store.getAt(index);
			record.set(this.dataIndex, !record.data[this.dataIndex]);
		}
	},

	renderer : function(v, p, record) {
		p.css += ' x-grid3-check-col-td';
		return '<div class="x-grid3-check-col' + (v ? '-on' : '')
				+ ' x-grid3-cc-' + this.id + '">&#160;</div>';
	}
};
/****end****/
		
function showUrl(value)
{
return "<a href='#'>"+value+"</a>";
}

Ext.onReady(function() {
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';   
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); 
		
	var tpl = '<tpl for="."><div class="x-combo-list-item" ext:qtitle="值" ext:qtip="{name}">{name}</div></tpl>'; 
	
	var data = [
	
					[1, 'EasyJWeb', 'EasyJF', 'www.easyjf.com','1900-5-6',66,'0',true],
					[2, 'jfox', 'huihoo', 'www.huihoo.org','2009-5-6',11,'1',false],
					[3, 'jdon', 'jdon', 'www.jdon.com','2009-5-6',22,'1',false],
					[4, 'springside', 'springside', 'www.springside.org.cn','1992-5-6',33,'0',false],
					[5, 'aaa', 'springside', 'www.easyjf.com','1999-5-6',45,'1',false],
					[6, 'bbb', 'springside', 'www.easyjf.com','1992-5-6',55,'0',false],
					[7, 'cccc', 'springside', 'www.easyjf.com','1992-5-6',66,'1',true],
					[8, 'ddd', 'yahoo', 'www.easyjf.com','1992-5-6',77,'0',false],
					[9, 'eee', 'ddddddddddddddd', 'www.springside.org.cn','1992-5-6',1230,'0',false],
					[10, 'fff', 'fdfsdafsdfs', 'www.yahoo.com.cn','1992-5-6',32,'0',false],
					[11, 'gggg', 'this is pen', 'www.yahoo.com.cn','1992-5-6',45,'0',true],
					[12, 'hhhh', 'springside', 'www.baidu.com','1992-5-6',56,'1',false],
					[13, 'as', 'springside', 'www.baidu.com','1992-5-6',756,'0',true],
					[14, 'you', 'how are you', 'www.baidu.com','1992-5-6',4455,'1',false],
					[15, 'hom', 'springside', 'www.springside.org.cn','1992-5-6',98,'0',false],
					[16, 'fff', 'springside', 'www.yahoo.com.cn','1992-5-6',676,'1',true],
					[17, 'gggg', 'springside', 'www.yahoo.com.cn','1992-5-6',555,'0',false],
					[18, 'fff', 'springside', 'www.yahoo.com.cn','1992-5-6',890,'1',false],
					[19, 'gggg', 'springside', 'www.yahoo.com.cn','1992-5-6',1200,'1',true],
					[20, 'fff', 'springside', 'www.jdon.com','1992-5-6',1566,'1',false],
					[21, 'gggg', 'springside', 'www.jdon.com','1992-5-6',333,'0',true],
					[22, 'gggg', 'springside', 'www.jdon.com','1255-5-6',333,'1',false],
					[23, 'vvvvv', 'tttttt', 'www.jdon.com','1992-5-6',333,'0',false],
					[24, 'sex', 'springside', 'www.jdon.com','2111-5-6',333,'1',true],
					[25, 'zhangsan', 'springside', 'www.jdon.com','1988-5-6',333,'0',true]
			
				];
		
		/**	
	var store = new Ext.data.SimpleStore({
		data : data,
		fields : ["id", "name", "organization", "homepage",{
			name : "beginDate",
			type : "date",
			dateFormat : "Y-n-j"
		}]
	});
	**/
	
	var sexData=[['女','1'],['男','0']];
	
	var sexComStore = new Ext.data.SimpleStore({
             fields: ['name', 'value'],
             data : sexData,
           	 sortInfo:{field:'name', direction:'ASC'} //指定排序字段
             
     });
	var sm=new Ext.grid.CheckboxSelectionModel();
	
	var reader = new Ext.data.ArrayReader({},[
       {name: 'id'},
       {name: 'name',type: 'string'},
       {name: 'organization'},
       {name: 'homepage'},
       {name: 'beginDate', type: 'date', dateFormat: 'Y-n-j'},
       {name: 'price', type: 'float'},
       {name: 'itemrslt'},
       {name: 'married',type: 'bool'}
    ]);
    
    var store = new Ext.data.GroupingStore({
            reader: reader,
            data: data,
            groupOnSort: false,
            sortInfo:{field: 'price', direction: "ASC"},
            groupField:'homepage'
    });
	
	 // 自定义的字段
     var checkColumn = new Ext.grid.CheckColumn({
        header: "婚否?",
        dataIndex: 'married',
        width: 55
     });
	
	
	var colM = new Ext.grid.ColumnModel([
	new Ext.grid.RowNumberer({header:"序号",width:60}),
	sm,
	{
		header : "ID",
		dataIndex : "id",
		sortable : true
	},
	{
		header : "项目名称",
		dataIndex : "name",		
		fixed : true,    //如果为真列宽不能被改变
		hidden : true,    //隐藏本列
		width : 60,
		editor : new Ext.form.TextField(),
		sortable : true
	}, {
		header : "开发团队",
		dataIndex : "organization",
		editor : new Ext.form.TextField(),
		//hidden:true,/*隐藏列*/
		sortable : true
	}, {
		header : "开始日期",
		dataIndex : "beginDate",		
		renderer : Ext.util.Format.dateRenderer('Y年m月d日'),
		editor : new Ext.form.DateField({
			format : 'Y年m月d日'
		}),
		sortable : true
	}, {
		header : "网址",
		dataIndex : "homepage",
		editor : new Ext.form.TextField(),
		renderer : showUrl
	}, {
		header : "金额",
		dataIndex : "price",
		//align: 'right',
		editor : new Ext.form.NumberField({
				 	allowNegative: false, // 不允许为负数
				 	decimalPrecision: 1, // 默认的小数点位数
				 	allowDecimals: false, // 不允许为负数
				 	maxValue: 100000 // 最大值为10万 		
		}),
		css:'text-align:right;',
		renderer : Ext.util.Format.usMoney 
	},
	{
		header : "性别",
		dataIndex : 'itemrslt',
		css : 'text-align: center;',
		horizontal:true, 
		renderer: rend,
		editor : new Ext.grid.GridEditor( new Ext.form.ComboBox({ 
         displayField: 'name', 
         valueField: 'value', 
         typeAhead: true,         
         triggerAction: 'all', 
         style: 'width:30px', 
         width:100, 
         tpl :tpl, 
         hiddenName:'sex', 
         mode: 'local',
         autoLoader:true, 
         selectOnFocus:true, 
         //lazyRender :true, 
         store: sexComStore 
		}))
		
	},
	 checkColumn // 自定义的婚否列
	]);
	colM.defaultSortable = true; 	
		
	function rend(value) {
        if (value == '0') { 
            return "男"; 
        } else {
            return "女"; 
        }
    }
	//Ext.util.Format.dateRenderer('m/d/Y')
	
	// 创建数据源的记录,代表一个员工
	var Employee = Ext.data.Record.create([
	{
		name : 'id',
		type : 'int'
	},
	{
		name : 'name',
		type : 'string'
	}, 
	{name: 'organization'},
	{name: 'homepage'},		
	{
		name : 'beginDate',
		mapping : 'birth',
		type : 'date',
		dateFormat : 'm/d/Y'
	}, // 日期自动转换
	 {
		name : 'price',
		type : 'float'
	},
	{name: 'itemrslt'},
	 {
		name : 'married',
		type : 'bool'
	}]);
	
	var ptb=new Ext.PagingToolbar({ 
			pageSize: 10, 
			store: store,
			displayInfo: true,
			height: 30,
			width: 800,
			items : [' 每页', new Ext.form.ComboBox({
			width : 50,	
			store : new Ext.data.SimpleStore({
				fields : ['Label', 'Value'],
				
				data : [[10, 10], [15, 15], [20, 20], [30, 30], [40, 40],[50, 50],
						[60, 60],[70, 70], [80, 80], [100, 100]]
				}),
			displayField : 'Label',
			valueField : 'Value',
			typeAhead : true,
			mode : 'local',
			value : 20,
			listWidth: 50, /** 行宽	**/	
			triggerAction : 'all',
			selectOnFocus : true,
			listeners : {
				change : {
					fn : function(box, newValue, oldValue) {						
						grid.changePageSize(newValue);
						
					}
				},
				select : {
					fn : function(combo, value) {					
						
					}
				}
			}
			})],
			displayMsg: '显示第 {0} 条到 {1} 条记录,  共 {2} 条', 
			emptyMsg: '没有记录' 
		});
		var view=new Ext.grid.GridView({forceFit:true,sortAscText :'正序', sortDescText :'倒序'});
		
	
	var grid = new Ext.grid.EditorGridPanel({
		//renderTo : "hello",
		title : "中国Java开源产品及团队",
		
		width : 800,
		frame: true,		
		cm : colM,
		sm: sm,
		store : store,		
		autoExpandColumn : 2, //默认自动扩展宽度的字段 
		clicksToEdit: 1, //属性定义点击几次进行编辑 clicksToEdit:1,//单击一次编辑
		loadMask: true, 
		loadMask:{msg:'正在加载数据......'},
    	bodyStyle:'width:100%',
		stripeRows:true, 
		autoHeight: true,
		plugins: checkColumn,
		viewConfig:{forceFit:true}, 
		animCollapse: false,
		
		view: new Ext.grid.GroupingView({ 
            forceFit:true, 
            sortAscText :'正序',
            sortDescText :'倒序',
            columnsText:'列显示/隐藏',
            groupByText:'依本列分组',
            showGroupsText:'分组显示',
            
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "项" : "项"]})',
            getRowClass: function(record,rowIndex,rowParams,store){// 数据显示红色
	                    		if(record.data.price>200){
										return 'x-grid-record-red';   
								 }else{
										return '';
								 }
							}
        }), 
		bbar: ptb,		
		tbar: [{ /** 顶部的工具栏 tools bar**/
                    text: '增加新员工',
                    handler : function(){
                        var p = new Employee({
                        	id: '',
                            name: '输入员工姓名',
                            organization: '',
                            homepage: '',
                            beginDate: (new Date()).clearTime(),
                            price: 0,
                            itemrslt: '0',
                            married: false
                        });                        
                        grid.stopEditing();
                        store.insert(0, p);
                        grid.startEditing(0, 0);                        
                    }
                }],
       
		listeners : {
			'celldblclick' : function() {
				
				//return false;  //返回false将双击不能变成可编辑状态
			},
			'cellcontextmenu' : function(g, r, c, e) {
				e.stopEvent();
				var menu = new Ext.menu.Menu({
					items : [{
						text : '编辑',
						handler : function() {
							g.startEditing(r, c);
						}
					}]
				});
				menu.showAt(e.getXY());
			}
		},
		changePageSize : function(pageSize) {
						if (pageSize != null && pageSize != '' && pageSize > 0 && pageSize != pagetb.pageSize) {
							pagetb.pageSize = parseInt(pageSize);
							this.store.load({
								params : {
									start : 0,
									limit : pagetb.pageSize
								}
							});
						}
		}
		
	});
	
	//store.load();
	
	grid.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
		var selectionModel = grid.getSelectionModel(); //资源Grid表中取出选中行
		var record = selectionModel.getSelected(); //取出对应记录
	});

	//grid.addListener('cellclick', cellclick);
	function cellclick(grid, rowIndex, columnIndex, e) {
	    var record = grid.getStore().getAt(rowIndex);   //Get the Record
	    var fieldName = grid.getColumnModel().getDataIndex(columnIndex);  //Get field name
	    var data = record.get(fieldName);
	    Ext.MessageBox.alert('提示','当前选中的数据是'+data);
	}		
	

	
	var win = new Ext.Window({
		title : '可编辑表格',
		modal : true,
		width : 900,
		autoScroll : true,
		closable : true,
		// resizable:true,
		items : [grid],
		x:200,
		y:5,
		buttons : [
			new Ext.Button({   
                text:"保存",
                minWidth:100,   
                id:"mybutton",
                //点击事件   
                listeners:{  
                    "click":function(){
                    	
                    	var m = store.getModifiedRecords();
						if (m.length == 0) {
							alert("没有更新的数据");
							return false;
						}
                    	var sSend = "["
						for (var i = 0, len = m.length; i < len; i++) {//married
							sSend = sSend + "{id:'" + m[i].data['id'] + "', married:'"+ m[i].data['married']+"'homepage:'"+ m[i].data['homepage']+ "',name:'"+m[i].data['name']+"',price:'"+m[i].data['price']+"', beginDate:'"+ m[i].data['beginDate'] +"'}";
							if (i < len - 1)
								sSend = sSend + ","
						}
						sSend = sSend + "]";
						sSend = Ext.util.JSON.encode(sSend);
						  
						alert(sSend);            
						//win.hide();
						win.close();
                    }
                }  
        })
		]
	})
	win.show();
	
});
</script>
	</head>
	<body>

<%--		<div id="hello"></div>--%>
	</body>
</html>

 

你可能感兴趣的:(JavaScript,css,ext,Yahoo,prototype)