首页 > 其他 > 详细

[学习记录] SessionStorage与LocalStorage

时间:2019-06-11 20:44:45      阅读:97      评论:0      收藏:0      [点我收藏+]

SessionStorage与LocalStorage都是可以用来创造本地存储的键值对,实现校验等等。

核心方法如下

创建键值对

window.sessionStorage.setItem("key","value");

获取值

var   getvalue=window.sessionStorage.getItem("key");

删除指定键

window.sessionStorage.removeItem("key");

清空所有值

window.sessionStorage.clear();

 

 

然后把上面的session换成local就是localstorage对应的函数了

 

 一下是一个简单的例子,用户可以点击create创建一个记录,点击check查看是否已存在记录,点击delete删除记录,可以看到当网页关闭的时候sessionstorage存储的数据丢失了,但localstorage仍然保存。

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <meta charset="utf-8">
 5     <title>honki</title>
 6   </head>
 7   <body>
 8     <div> hello this is ss</div>
 9     <div id="whoss">who are you</div>
10     <button type="button" name="button1ss" onclick="createss()"> create </button>
11     <button type="button" name="button2ss" onclick="checkss()"> check </button>
12     <button type="button" name="button3ss" onclick="delss()"> delete </button>
13 
14     <div> hello this is lo</div>
15     <div id="wholo">who are you</div>
16     <button type="button" name="button1lo" onclick="createlo()"> create </button>
17     <button type="button" name="button2lo" onclick="checklo()"> check </button>
18     <button type="button" name="button3lo" onclick="dello()"> delete </button>
19     <!-- built files will be auto injected -->
20   </body>
21   <script type="text/javascript">
22   function createss(event){
23     window.sessionStorage.removeItem(id);
24     window.sessionStorage.setItem(id,"wang");
25     document.getElementById(whoss).innerHTML=you are wang;
26   }
27 
28   function checkss(event){
29     if (window.sessionStorage.getItem(id)===wang)
30     {
31       document.getElementById(whoss).innerHTML=you are wang;
32     }
33     else
34     {
35       document.getElementById(whoss).innerHTML=sorry please create;
36     }
37   }
38 
39   function delss(event){
40     window.sessionStorage.clear();
41     document.getElementById(whoss).innerHTML=who are you;
42   }
43 
44   function createlo(event){
45     window.localStorage.removeItem(id);
46     window.localStorage.setItem(id,"wang");
47     document.getElementById(wholo).innerHTML=you are wang;
48   }
49 
50   function checklo(event){
51     if (window.localStorage.getItem(id)===wang)
52     {
53       document.getElementById(wholo).innerHTML=you are wang;
54     }
55     else
56     {
57       document.getElementById(wholo).innerHTML=sorry please create;
58     }
59   }
60 
61   function dello(event){
62     window.localStorage.clear();
63     document.getElementById(wholo).innerHTML=who are you;
64   }
65   </script>
66 </html>

 

[学习记录] SessionStorage与LocalStorage

原文:https://www.cnblogs.com/trickofjoker/p/11005590.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!