简体   繁体   English

刷新页面后的本地存储项目

[英]local storage items after refresh page

 <!DOCTYPE html> <html> <body> <button onclick="myFunction();">Fav Number</button> <div id="result"></div> <!--This code works on chrome--> <script> function myFunction() { // Check browser support if (typeof(Storage) !== "undefined") { // Store var a = prompt("fav number"); localStorage.setItem("lastname", a); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname"); } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage..."; } } </script> </body> </html> 

hello, 你好,

is it possible to get local storage items back when you refresh the page? 刷新页面时是否可以取回本地存储项目? and if so, how? 如果是这样,怎么办?

Thanks 谢谢

Dylan, 迪伦

Getting and setting localStorage data. 获取和设置localStorage数据。 In following example the data to set is a Object (which is handled by JSON.stringify ). 在以下示例中,要设置的数据是一个Object (由JSON.stringify处理)。 If need to persist a string / int there is no need in using JSON.stringify . 如果需要保留string / int ,则无需使用JSON.stringify

var dataObject = { 'item1': 1, 'item2': 2, 'item3': 3 };

// Set localStorage item
localStorage.setItem('dataObject', JSON.stringify(dataObject));

// Retrieve the object from localStorage
var retrievedObject = localStorage.getItem('dataObject');

// console.log retrieved item
console.log('retrieved data Object: ', JSON.parse(retrievedObject));

By getting localStorage data when needed, there no need to handle the page refresh part. 通过在需要时获取localStorage数据,无需处理页面刷新部分。 The localStorage data is fetched when needed by application functions and logics. 应用程序功能和逻辑在需要时会提取localStorage数据。

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

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