诀窍是:
- 为每个选定的行保存一些指示
- 在构建过滤数据时,请注意在数组中选择了哪些行
- 在“setGridData”之后调用“setSelectedRows”
这是执行此操作的代码。
// filter grid without harming selection
// grid: a SlickGrid Object
// filter: a function that receieves a "data row" and returns true if it meets the filter
function filterGrid(grid,filter) {
var oldline;
var olddata=grid.getData();
var oldselection=grid.getSelectedRows()
var newline=0;
var newdata=[];
var newselection=[];
for (oldline=0; oldline<olddata.length ; oldline++ ) {
if (filter(olddata[oldline]) {
newdata.push(olddata[oldline]);
if (oldselection.indexOf(oldline)>-1) { // note on condition: ECMA5 - in IE8 you will need to loop
newselection.push(newline);
newline++;
}
}
}
grid.setData(newdata);
grid.setSelectedRows(newselection);
grid.updateRowCount();
grid.render();
}
请注意,此代码不会保留未通过过滤器的选定行。