[英]Persisting data on the page on refresh
我想在页面刷新之前保留目标有序列表的数据,然后在准备好文档时使用jquery对其进行添加。 这是我的代码
// 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>
但是刷新结果后,代码无法按预期工作,请在此处输入图像描述
尽管在刷新之前已在此处输入图片描述
您需要使用localStorage
因为存储在localStorage
数据将一直保留到明确删除为止。 所做的更改将被保存,并可供当前和将来对该站点的所有访问。
对于sessionStorage
,更改仅在每个窗口(或Chrome和Firefox等浏览器中的选项卡)上可用。 所做的更改将被保存,并且可用于当前页面以及将来在同一窗口上访问该站点。 关闭窗口后,将删除存储。
关于此链接的更多详细信息https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
谢谢@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.