如何在EXTJS 3.2.1中为Grid添加文本框实现实时过滤?
实现ExtJS Grid实时文本过滤方案
没问题,我来帮你搞定这个Grid实时过滤的需求!先帮你修正原代码里的几个小语法问题,再一步步实现过滤功能:
第一步:修正原代码的基础问题
你的原代码里有两处小错误:
ColumnModel中NameCourse列的配置多了一个多余的逗号- 变量定义顺序不对,应该先定义
record,再定义xmlStore,最后创建Grid组件
第二步:添加过滤文本框与实时过滤逻辑
我们可以给Grid添加顶部工具栏(tbar),在里面放一个文本输入框,然后监听输入框的keyup事件,实时调用Store的filterBy方法来过滤数据,匹配你指定的列内容。
完整实现代码
Ext.onReady(function () { // 先定义Record结构 var record = Ext.data.Record.create([ { name: 'CourseId', type: 'int' }, { name: 'ActionCenterId', type: 'int' }, { name: 'NameCourse', type: 'string' }, { name: 'ActionCenterName', type: 'string' } // 补充这个字段,原代码里Grid列用到了但Record没定义 ]); // 定义Store var xmlStore = new Ext.data.Store({ url: "Services/course/courseService.aspx?serviceMethod=GetcourseDetails", reader: new Ext.data.XmlReader({ record: 'Course', totalRecords: 'results' }, record ) }); // 创建过滤文本框 var filterTextField = new Ext.form.TextField({ emptyText: '输入关键词过滤...', width: 200, enableKeyEvents: true, // 启用键盘事件监听 listeners: { keyup: function(field, e) { var filterValue = field.getValue().toLowerCase(); // 调用Store的filterBy方法实现自定义过滤 xmlStore.filterBy(function(record) { // 匹配NameCourse和ActionCenterName两个列,忽略大小写 var courseName = record.get('NameCourse').toLowerCase(); var centerName = record.get('ActionCenterName').toLowerCase(); return courseName.indexOf(filterValue) !== -1 || centerName.indexOf(filterValue) !== -1; }); } } }); // 创建Grid组件 var reportsGrid = new Ext.grid.GridPanel({ id: 'my-grid', cm: new Ext.grid.ColumnModel([ { id: 'CourseId', dataIndex: 'CourseId', hidden: true }, { dataIndex: 'ActionCenterId', hidden: true }, { header: 'AAAAA', width: 115, sortable: true, dataIndex: 'NameCourse' }, // 去掉了多余的逗号 { header: 'BBBB', width: 100, sortable: true, dataIndex: 'ActionCenterName' } ]), tbar: [filterTextField], // 将过滤文本框加入Grid顶部工具栏 maxHeight: 350, autoHeight: true, width: 870, store: xmlStore, title: 'SEARCH' }); // 渲染Grid并加载数据 reportsGrid.render('ext_grid_results'); xmlStore.load(); // 记得加载Store数据 });
关键说明
enableKeyEvents: true:必须开启这个配置,文本框才能监听keyup事件filterBy方法:这是ExtJS Store提供的自定义过滤方法,我们可以自己定义过滤规则,这里实现了对NameCourse和ActionCenterName两个列的模糊匹配,并且忽略大小写- 顶部工具栏
tbar:把文本框放在Grid的头部工具栏,符合你“在Grid头部添加文本框”的需求 - 补充了
ActionCenterName字段到record中,因为你的Grid列用到了这个数据索引,但原代码里没定义
这样就能实现输入字符时实时过滤Grid里的数据啦!
内容的提问来源于stack exchange,提问作者shapir
相关产品推荐
相关产品推荐

