1.sessionStorage
sessionStorage 只会在关闭窗口前有效,只要窗口关闭,数据就会立刻删除
实例:
function testCount() {
var storage = window.sessionStorage;
var itemKey='key';
if (itemKey) {
var oldCount = storage.getItem(itemKey);
var count = 0;
if (oldCount == null) {
count = 1;
} else {
count = parseInt(oldCount) + 1;
}
//保存数据
storage.setItem(itemKey, count);
if (count >= 3) {
//10秒后调用testB函数
setTimeout('testB()', 10000);
}
}
}
function testB() {
alert("3次以上啦");
}
2.cookie
cookie 默认的生命周期是浏览器关闭的时失效
实例:
function addCount() {
var itemKey='key';
if (itemKey) {
var oldCount = $.cookie(itemKey);
var count = 0;
if (oldCount == null) {
count = 1;
} else {
count = parseInt(oldCount) + 1;
}
//保存数据
$.cookie(itemKey, count);
if (count >= 3) {
//10秒后调用testB函数
setTimeout('testB()', 10000);
}
}
}
function testB() {
alert("3次以上啦");
}
3.localStorage
localStorage 可以将第一次请求的数据直接存储到本地,属于永久性存储,关闭浏览器后下次再打开数据还存在,除非你手动删除
function testCount() {
var storage = window.localStorage ;
var itemKey='key';
if (itemKey) {
var oldCount = storage.getItem(itemKey);
var count = 0;
if (oldCount == null) {
count = 1;
} else {
count = parseInt(oldCount) + 1;
}
//保存数据
storage.setItem(itemKey, count);
if (count >= 3) {
//10秒后调用testB函数
setTimeout('testB()', 10000);
}
}
}
function testB() {
alert("3次以上啦");
}