简体   繁体   English

刷新时在页面上保留数据

[英]Persisting data on the page on refresh

I want to keep the data of the target ordered list before page refresh and then prepend it using jquery on document ready. 我想在页面刷新之前保留目标有序列表的数据,然后在准备好文档时使用jquery对其进行添加。 Here is my code 这是我的代码

 // if an refresh event is fired window.onbeforeunload = function(event){ //store the messages into sessionStorage sessionStorage.setItem('ol', jQuery('#messages')); return undefined; }; $(document).ready(function(){ if (sessionStorage.getItem('ol')) { // Restore the contents of the ol (message contents) var ol = sessionStorage.getItem('ol'); jQuery('#messages').html(ol); } }); 
 <div class="chat__main"> <ol id="messages" class="chat__messages"></ol> <div class="chat__footer"> <form id="message-form" action=""> <input type="text" name="message" placeholder="Message" autofocus autocomplete="off"/> <button>Send</button> </form> <button id="send-location"> Send location</button> </div> </div> 

But the code is not working as expected after refreshing the result is enter image description here 但是刷新结果后,代码无法按预期工作,请在此处输入图像描述

Although before refreshing it was enter image description here 尽管在刷新之前已在此处输入图片描述

You need to use localStorage As data stored in localStorage persists until explicitly deleted. 您需要使用localStorage因为存储在localStorage数据将一直保留到明确删除为止。 Changes made are saved and available for all current and future visits to the site. 所做的更改将被保存,并可供当前和将来对该站点的所有访问。

For sessionStorage , changes are only available per window (or tab in browsers like Chrome and Firefox). 对于sessionStorage ,更改仅在每个窗口(或Chrome和Firefox等浏览器中的选项卡)上可用。 Changes made are saved and available for the current page, as well as future visits to the site on the same window. 所做的更改将被保存,并且可用于当前页面以及将来在同一窗口上访问该站点。 Once the window is closed, the storage is deleted. 关闭窗口后,将删除存储。

More details on this link https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage 关于此链接的更多详细信息https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Thanks @charlietfl Here is what works for me 谢谢@charlietfl这对我有用

 // if an refresh event is fired window.onbeforeunload = function(event){ //store the messages into sessionStorage sessionStorage.setItem('ol', jQuery('#messages').html()); return undefined; }; $(document).ready(function(){ if (sessionStorage.getItem('ol')) { // Restore the contents of the ol (message contents) var ol = sessionStorage.getItem('ol'); jQuery('#messages').html(ol); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM