[英]Localstorage not storing
I'm trying to save the page state when a user looks at an item from search results then goes back to the results. 当用户查看搜索结果中的项目然后返回结果时,我试图保存页面状态。
The surrounding div has an id of mainContainer
so its basically everything in there that i want to save and then restore. 周围的div具有
mainContainer
的ID,因此它基本上要保存然后还原的所有内容。
I'm using native javascript, not jquery. 我正在使用本机javascript,而不是jquery。
Here's what I'm trying: 这是我正在尝试的:
// Replace the search results on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myPage' in localStorage && window.location.hash) {
var el = document.getElementById('mainContainer');
el.innerHTML = localStorage.getItem('myPage');
}
}
// Save the search results when leaving the page.
window.onbeforeunload = function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var el = document.getElementById('mainContainer');
var form = el.innerHTML;
localStorage.setItem('myPage', form);
}
};
As far as i can see, your code has a syntax error 据我所知,您的代码有语法错误
Uncaught SyntaxError: Unexpected token )
未捕获到的SyntaxError:意外令牌)
window.onbeforeunload = function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var el = document.getElementById('mainContainer');
var form = el.innerHTML;
localStorage.setItem('myPage', form);
}
});
//^Here
Other than that it seems to work fine: JSFiddle . 除此之外,它似乎还可以正常工作: JSFiddle 。 Just change the content in HTML an run the fiddle again, previous
HTML
will be stored and will be reloaded. 只需更改HTML中的内容,然后再次运行小提琴,先前的
HTML
将被存储并重新加载。 ( BTW I removed the hash check for demo purpose ) ( 顺便说一句我出于演示目的删除了哈希检查 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.