JS如何缓存一个变量 [英] JS how to cache a variable

查看:171
本文介绍了JS如何缓存一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是能够创建一个变量,给它一个值,关闭并重新打开窗口,并能够检索我在上一次会话中设置的值。什么是最简单的方法来做到这一点?欢迎使用JQuery的答案。

使用 localStorage



写作:

  localStorage ['myKey '] ='somestring'; //只有字符串

阅读:

  var myVar = localStorage ['myKey'] || '默认值'; 

如果您需要存储复杂的结构,可以使用JSON序列化它们。例如:

阅读:

  var stored = localStorage [我的钥匙']; 
if(stored)myVar = JSON.parse(stored);
else myVar = {a:'test',b:[1,2,3]};

写作:

  localStorage ['myKey'] = JSON.stringify(myVar); 

请注意,您可能使用多个键。它们都将被同一域中的所有页面检索到。



除非您想与IE7兼容,否则您没有理由使用过时的小Cookie。

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the simplest way to do that? JQuery answers are welcome.

解决方案

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

这篇关于JS如何缓存一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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