我需要添加类似于 Gmail 的功能,其中项目列表上的复选框会在多个结果页面以及离开和返回结果时记住.我想弄清楚的是最好的方法.我正在使用 PHP,可能还有 jQuery.
I'm needing to add functionality similar to Gmail where the checkboxes on a list of items is remembered across multiple pages of results and when going away and coming back to the result. What I'm trying to figure out is the best way of doing this. I'm using PHP and likely jQuery.
我的第一个想法是向每个复选框添加一个 onClick,以触发 AJAX 调用返回服务器,该服务器将 id 存储在会话中的数组中.每次加载项目列表时,系统都会检查该行是否被选中,并在必要时选中复选框.为了可靠性,在检查到服务器的请求是否无法完成(连接问题、服务器错误等)后,将取消选中该复选框,并尽可能快地发出请求.
My first thought is to add an onClick to each checkbox that triggers an AJAX call back to the server which stores the id in an array in the session. Each time a list of items is loaded, the system would check to see if the row is checked and check the checkbox if necessary. For reliability, the checkbox would be unchecked after checking if the request to the server cannot be completed (connection problem, server error, etc) and the request would be made as quick as absolutely possible.
这听起来都不错,除了一些项目:
This sounds all good, except for a few items:
过去我没有找到一种可靠的方法来检测用户何时离开页面.如果有可靠的方法,那么我可以将其视为一个选项,因此它只会在每个页面卸载时进行记录.
In the past I haven't found a reliable way to detect when the user leaves a page. If there is a reliable way, then I could see this being an option so it just records on each page unload.
是否有其他解决方案或更好的方法?
Are there any other solutions or better methods?
如Eran Galperin,check all 方法只需要检查每个复选框,然后对所有行进行 ajax 调用.无需删除 onClick.
As mentioned by Eran Galperin, the check all method would only need to check each of the checkboxes and then make an ajax call with all of the rows. No need to remove the onClick.
另外,看起来事件委托方法是个好主意——会让事情变得更容易.
Also, it looks like the Event Delegation method is a good idea—would make things a lot easier.
对于离开页面的用户,您可以使用 onbeforeonload事件,但是如果浏览器崩溃或以其他方式不正常退出,它将不会被捕获.根据捕获用户更改的关键程度来使用它.
For a user leaving the page you can use the onbeforeonload event, however if the browser crashes or otherwise exits ungracefully it will not be caught. Use it depending on how critical is it to be able to capture user changes.
这篇关于记住跨页面选中的复选框 - 最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!