【发布时间】:2018-06-24 11:38:42
【问题描述】:
我想在页面刷新之前保留目标有序列表的数据,然后在文档准备好时使用 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>
但是刷新结果后代码没有按预期工作 enter image description here
虽然在刷新之前是 enter image description here
【问题讨论】:
-
我建议您查看JS Cookie,因为它确实可以帮助您更好地管理您的 cookie。它将使无需服务器端代码的持久数据变得更加容易。
-
无法将 jQuery 对象作为存储值传递。只能在存储中存储字符串。
-
@Schalk.Netgen 建议您阅读存储的工作原理。 Cookie 不是做这种事情的好选择
-
我确实想保存目标 jQuery('#messages') 的内容
-
从该元素获取 html,然后
sessionStorage.setItem('ol', jQuery('#messages').html());
标签: javascript jquery html