|
@@ -0,0 +1,81 @@
|
|
|
+<!DOCTYPE html>
|
|
|
+<html lang="en">
|
|
|
+<head>
|
|
|
+ <meta charset="UTF-8">
|
|
|
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
+ <title>Document</title>
|
|
|
+</head>
|
|
|
+<body>
|
|
|
+ <!--
|
|
|
+ cookie 与 webStorage的区别
|
|
|
+ 1.cookie会与服务器交互(速度变慢);
|
|
|
+ 2.cookie储存大小约4kb;
|
|
|
+ 3.webStorage是把数据储存到客户端,不会和服务器交互,可随机获取(速度快);
|
|
|
+ 4.webStorage储存大小是5MB,可储存的数据更大;
|
|
|
+ 注意:webStorage就是为了弥补cookie的缺陷;
|
|
|
+ 5.对于临时存储的数据使用sessionStorage更方便;
|
|
|
+ 6.webStorage不参与服务器通信,储存在本地更安全;
|
|
|
+ 7.webStorage中的键值对必须是字符串;使用时需要转JS对象;
|
|
|
+ -->
|
|
|
+ <!--
|
|
|
+ webStorage: 5MB 不和服务端交互 速度更快 存在独立域
|
|
|
+ 缺点:不同域之间无法访问 数据如果不删除 会长期存在 缺乏安全性
|
|
|
+ 本地存储:localStorage 只要不手动删除 就会一直存在
|
|
|
+ 会话存储: sessionStorage 只要关闭页面 数据自动销毁
|
|
|
+ -->
|
|
|
+ <!--
|
|
|
+ 1.存放数据:
|
|
|
+ 1.localStorage/sessionStorage.settItem("属性名","属性值");
|
|
|
+ 2.localStorage/sessionStorage.属性名 = 属性值;
|
|
|
+ 3.localStorage/sessionStorage["属性名"] = 属性值;
|
|
|
+ 2.读取数据:
|
|
|
+ 1.localStorage/sessionStorage.getItem("属性名");
|
|
|
+ 2.localStorage/sessionStorage.属性名;
|
|
|
+ 3.localStorage/sessionStorage["属性名"];
|
|
|
+ 3.删除一条数据
|
|
|
+ 语法:localStorage/sessionStorage.removeItem("属性名");
|
|
|
+ 4.清除所有的数据
|
|
|
+ 语法:localStorage/sessionStorage.clear();
|
|
|
+ 5.得到某个索引的key;
|
|
|
+ 语法:localStorage/sessionStorage.key(下标);//注意:下标是整数;
|
|
|
+ 例如:localStorage/sessionStorage.key(0);//得到第一个数据的属性名;
|
|
|
+ 检测某个属性是否是私有属性(非继承)
|
|
|
+ 语法:对象.hasOwnProperty("属性名");
|
|
|
+
|
|
|
+
|
|
|
+ -->
|
|
|
+ <button id="btn1">删除名字</button>
|
|
|
+ <button id="btn2">清除所有数据</button>
|
|
|
+ <button id="btn3">获取年龄</button>
|
|
|
+ <script>
|
|
|
+ var btn1 = document.getElementById("btn1");
|
|
|
+ var btn2 = document.getElementById("btn2");
|
|
|
+ var btn3 = document.getElementById("btn3");
|
|
|
+ // 必须是字符串键值对
|
|
|
+ let obj1 = {
|
|
|
+ a:"哈哈",
|
|
|
+ b:"大大"
|
|
|
+ }
|
|
|
+ sessionStorage.setItem("obj",JSON.stringify(obj1));
|
|
|
+ console.log(sessionStorage.key(0))
|
|
|
+ console.log(JSON.parse(sessionStorage.getItem("obj")));
|
|
|
+ sessionStorage.setItem("name","明明");
|
|
|
+ sessionStorage.age = 18;
|
|
|
+ sessionStorage['sex'] = '女'
|
|
|
+ console.log(sessionStorage.getItem("name"));
|
|
|
+ console.log(sessionStorage.age);
|
|
|
+ console.log(sessionStorage["sex"]);
|
|
|
+ btn1.onclick = () =>{
|
|
|
+ sessionStorage.removeItem("name");
|
|
|
+ }
|
|
|
+ btn2.onclick = () => {
|
|
|
+ sessionStorage.clear();
|
|
|
+ }
|
|
|
+ btn3.onclick = () => {
|
|
|
+ console.log(sessionStorage.key(1));
|
|
|
+ }
|
|
|
+ console.log(sessionStorage.hasOwnProperty('name1'))
|
|
|
+
|
|
|
+ </script>
|
|
|
+</body>
|
|
|
+</html>
|