关于分页选中问题-超越昨天的自己系列(9)
关于分页选中问题
一些管理后台,可能会遇到这样的场景:几百条数据分页罗列出来后,需要最这些数据选中操作。比如我在第5页选中3条数据,返回到第4页再选1条,然后对4条数据进行处理。
能想到的比较原始的做法是这样的:
1,页面维持一个选中的数据容器
2,每次新查询,或者翻页,这些数据传回后台,后台再传回页面(不要使用session)
3,等到选择完毕后进行操作,就依照这个数据容器中的内容为准。
那么页面上维护住这个所谓的数据容器是关键:
比如说页面中的每条数据类似这种形式,每条数据前都有个checkbox来供选择:
#foreach($temp in $!{blacklist}) <tr align="center"> <td><input name="chk_id" id="chk_id" type="checkbox" value="$temp.phone"></td> <td>$temp.phone</td> <td>$!{dateUtil.formatDateTime($!temp.gmtLast)}</td> <td>$!{dateUtil.formatDateTime($!temp.gmtFirst)}</td> <td>$temp.loginCount</td> </tr> #end
下面三个方法,就直接实现了这个容器的存取数据功能,依照这个基础,选中和不选中的操作就比较简单了
var selectPhones ='$!{selectPhones}'.split(","); var selectPhonesNum = $!{selectPhonesNum}; function pushSelectPhone(phone){ if(checkSelectPhone(phone) == -1){ selectPhones.push(phone); selectPhonesNum++; jQuery("#selectPhones").val(selectPhones); jQuery("#selectPhonesNum").val(selectPhonesNum); jQuery("#showNum").html(selectPhonesNum); } } function sliceSelectPhone(phone){ var index = checkSelectPhone(phone); if(index != -1){ selectPhones.splice(index,1); selectPhonesNum--; jQuery("#selectPhones").val(selectPhones); jQuery("#selectPhonesNum").val(selectPhonesNum); jQuery("#showNum").html(selectPhonesNum); } } function checkSelectPhone(newPhone){ var index = -1; for (var i=0;i<=selectPhones.length-1;i++) { var oldPhone = selectPhones[i]; if(newPhone == oldPhone){ index = i; return i; } } return index; }
然后只要对每个checkbox进行绑定事件就好了:
jQuery("input[name='chk_id']").click(function(){ var phone = jQuery(this).attr("value"); if(jQuery(this).attr("checked")){ pushSelectPhone(phone); }else{ sliceSelectPhone(phone) } })
那么像全选啊,页面刷新进来的时候需要对这个页面已经选中过的数据表现为选中这些功能也是比较好实现了:
jQuery("#chk_all").click(function(){ if(jQuery(this).attr("checked")){ jQuery("input[name='chk_id']").each(function(index){ pushSelectPhone(jQuery(this).val()); }) }else{ jQuery("input[name='chk_id']").each(function(index){ sliceSelectPhone(jQuery(this).val()) }) } })
jQuery("input[name='chk_id']").each(function(index){ if(checkSelectPhone(jQuery(this).val()) != -1){ jQuery(this).attr("checked", "checked"); } })
这个功能应该是比较常见的,这儿是我本人的一个思路和实现,暂时还没想出另外比较好的实现方式。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述