localstorage保存数据

注意这个的原因是我最近在做大创项目,就是一个谷歌插件,其中我需要做一个日程表,那么这个课程表内容就需要保存下来。一开始我是想要用一个json或者txt的文件来保存它,但是失败了,这样会导致ajax的跨域问题。然后就想到session或者cookie,但是session一般是服务器端的操作,而清除cookie释放空间又会是我们学生常做的操作,在我打算查C++的资料做尝试前,我找到了这个,我好了= =。

首先先介绍一下localstorage

使用 localStorage 可以创建一个本地存储的 name/value 对,而且没有cookie的4k大小限制(但是一般都不会超过4k吧)

再看看localstorage用法

1
2
3
str = ["123","321"];            //value,是值或者list
localStorage.setItem("temp",str); //生成name为temp的键值对
console.log(localStorage.getItem("temp")); //取出来康康效果

另外,localstorage只能读取,所以对localstorage的增删查改就要通过删除重新赋值来实现

看看我目前的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$(function(){
if ( typeof(localStorage.temp) == "undefined" ){ //查看localStorage是否存在
console.log("没有");
str = [["","","","","","",""],
["","","","","","",""],
["","","","","","",""],
["","","","","","",""],
["","","","","","",""],
["","","","","","",""],
];

localStorage.setItem("temp",str);
console.log(localStorage.getItem("temp"));
} else {
console.log("有");
console.log(localStorage.getItem("temp"));
}



var obj = localStorage.getItem("temp").split(",");
console.log(obj);
var ht = '<thead><tr><th>Table table</th><th>Mon.</th><th>Tue.</th><th>Wed.</th><th>Thu.</th><th>Fri.</th><th>Sat.</th><th>Sun.</th></tr></thead><tbody>';
for(var i = 0 ; i < 6 ; i++){
ht = ht+'<tr>';
ht = ht + '<td>' + String(2*i+1) + '~' + String(2*i + 2) + '</td>';
for(var j = 0 ; j < 7 ; j++)
{
ht = ht + '<td>' + obj[7*i+j]+ '</td>';
}
ht = ht+'</tr>';
}
ht = ht + '</tbody>'
$('#tb').append(ht);
})

行吧,菜鸟到此为止,继续努力。