刷新页面后的本地存储项目 [英] local storage items after refresh page

查看:120
本文介绍了刷新页面后的本地存储项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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>

你好

刷新页面时是否可以取回本地存储项目? 如果是这样,怎么办?

is it possible to get local storage items back when you refresh the page? and if so, how?

谢谢

迪伦

推荐答案

获取和设置localStorage数据.在以下示例中,要设置的数据是Object(由JSON.stringify处理).如果需要坚持string/int,则无需使用JSON.stringify.

Getting and setting localStoragedata. In following example the data to set is a Object (which is handled by JSON.stringify). If need to persist a string / intthere is no need in using 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));

通过在需要时获取localStorage数据,无需处理页面刷新部分. localStorage数据在应用程序功能和逻辑需要时获取.

By getting localStorage data when needed, there no need to handle the page refresh part. The localStorage data is fetched when needed by application functions and logics.

这篇关于刷新页面后的本地存储项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆