w2ui Grid:搜索时保留选中状态的实现方法
如何在w2ui Grid搜索时保留选中状态
我创建了如下所示的w2ui Grid:
JavaScript 代码
$('#myGrid').w2grid({ name : 'myGrid', columns: [ { field: 'fname', text: 'First Name', size: '30%' }, { field: 'lname', text: 'Last Name', size: '30%' }, { field: 'email', text: 'Email', size: '40%' }, { field: 'sdate', text: 'Start Date', size: '120px' }, ], show: { toolbar: true, selectColumn: true }, records: [ { recid: 1, fname: 'John', lname: 'Doe', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 2, fname: 'Stuart', lname: 'Motzart', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 3, fname: 'Jin', lname: 'Franson', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 4, fname: 'Susan', lname: 'Ottie', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 5, fname: 'Kelly', lname: 'Silver', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 6, fname: 'Francis', lname: 'Gatos', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 7, fname: 'Mark', lname: 'Welldo', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 8, fname: 'Thomas', lname: 'Bahh', email: 'jdoe@gmail.com', sdate: '4/3/2012' }, { recid: 9, fname: 'Sergei', lname: 'Rachmaninov', email: 'jdoe@gmail.com', sdate: '4/3/2012' } ], searches: [ { field:'fname', label:'fname', type:'text', operator:'contains' }, { field:'lname', label:'lname', type:'text', operator:'contains' }, ] });
HTML 代码
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/w2ui@2.0.0/w2ui-2.0.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/w2ui@2.0.0/w2ui-2.0.min.css" rel="stylesheet"> <div id='myGrid' style='height:500px'></div>
我可以手动选中部分记录:
但遇到的问题是,当我搜索特定值时,之前选中的记录会取消选中状态:
(在该示例中,搜索'an'字符串后,'Francis Gatos'记录的选中状态消失)
请问是否有办法在应用搜索条件时保留选中状态?
解决方案
要实现搜索时保留选中状态,可通过监听Grid的搜索和刷新事件,保存并恢复选中记录:
方法一:通过onSearch事件处理
在搜索执行前保存选中的记录ID,搜索完成后重新选中仍在结果中的记录:
$('#myGrid').w2grid({ // 原有配置... onSearch: function(event) { // 搜索前保存所有选中记录的recid const selectedRecids = w2ui.myGrid.getSelection(); // 指定搜索完成后的回调 event.onComplete = function() { selectedRecids.forEach(recid => { // 检查记录是否存在于当前过滤后的结果中 if (w2ui.myGrid.get(recid)) { w2ui.myGrid.select(recid); } }); }; } });
方法二:通过onSearch和onRefresh事件配合
先在搜索前保存选中状态,再在Grid刷新后恢复:
let savedSelection = []; $('#myGrid').w2grid({ // 原有配置... onSearch: function() { // 保存当前选中的记录ID列表 savedSelection = w2ui.myGrid.getSelection(); }, onRefresh: function() { // 刷新完成后,恢复仍在结果中的选中记录 savedSelection.forEach(recid => { if (w2ui.myGrid.get(recid)) { w2ui.myGrid.select(recid); } }); } });
以上两种方法都能确保搜索后,原本选中且符合搜索条件的记录保持选中状态。
内容的提问来源于stack exchange,提问作者Stefano Radaelli
相关产品推荐
相关产品推荐

