通常,我们希望点击搜索之后,只留下符合条件的Record。而ExtJs4的搜索只是将符合条件的字段用黄体字标识出来。我将源文件中的LiveSearchGridPanel.js稍作修改以符合自己的需要。
首先来展示效果:
ExtJs4里面自带一种带搜索功能的表格LiveSearchGridPanel.js,放置在其目录下example文件下。我们的目标是将其进行修改,以使表格自动过滤那些不符合搜索条件的Record。
其中可以做文章的自然是onSearch文件
修改后的onSearch函数:
/**
* Finds all strings that matches thesearched value in each grid cells.
* @private
*/
onSearch: function() {
var me = this,
count = 0;
me.store.rejectChanges(); //每次搜索使都让上次的操作回滚
me.view.refresh(); //更新表中条目
me.statusBar.setStatus({ //这个是用来显示搜索结果数目的框,不必理会
text: me.defaultStatusText,
iconCls: ''
});
/* 取得搜索字符 */
me.searchValue = me.getSearchValue();
/* 记录当前索引在表格store中的位置 */
me.currentIndex = null;
if (me.searchValue !== null) {
me.searchRegExp = new RegExp(me.searchValue, 'g'+ (me.caseSensitive ? '' : 'i'));
/* 表格中的Record数目 */
var totalCount = me.store.getTotalCount();
//遍历所有条目,找出符合条件的Record
for ( idx = 0; idx < totalCount; idx ++ ) {
var record =me.store.getAt( idx );
vartd = Ext.fly(me.view.getNode( idx )).down('td'),
cell, matches, cellHTML;
/*在这一Record中是否有需要找寻的内容,默认false */
var find = false;
//遍历每条Record的每一列
while(td){
cell = td.down('.x-grid-cell-inner');
matches =cell.dom.innerHTML.match(me.tagsRe);
cellHTML =cell.dom.innerHTML.replace(me.tagsRe, me.tagsProtect);
cellHTML =cellHTML.replace(me.searchRegExp, function(m) {//找到目标
find= true;
if (Ext.Array.indexOf(me.indexes, idx) === -1) {
me.indexes.push(idx);
}
if (me.currentIndex === null) {
me.currentIndex =idx;
}
return '<span class="'+ me.matchCls + '">' + m + '</span>';
});
//restore protected tags
Ext.each(matches, function(match) {
cellHTML =cellHTML.replace(me.tagsProtect, match);
});
//update cell html
cell.dom.innerHTML =cellHTML;
td = td.next();
}
if ( ! find ){ //如果该行没有找到需要的结果
me.store.remove(record ); //则将该行从表格中移除
totalCount--;
idx--;
} else {
count++;
}
};
//results found
if(me.currentIndex !== null) {
me.getSelectionModel().select(me.currentIndex);
me.statusBar.setStatus({
text: '共找到'+ count + '条.',
iconCls: 'x-status-valid'
});
}
}
// no results found
if (me.currentIndex === null) {
me.getSelectionModel().deselectAll();
}
// force textfield focus
me.textField.focus();
}