HTML5 本地储存-cookie随堂笔记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTML5 本地储存-cookie随堂笔记相关的知识,希望对你有一定的参考价值。
一、PC端,用cookie
window.onload = function () {
document.cookie = "userCode=291382190";
document.cookie = "id=007";
};
二、移动端存储,用web stroage
(1)localStorage;会话时间,浏览器关闭即消失,临时保存
(2)sessionStorage;存储在本地硬件设备,浏览器关闭也会存在,永久保存
1、存储对象
(1)JSON.stringify;对象→字符串
(2)JSON.parse;字符串→对象.
2、增删查改
1 //移动端存储 2 //web stroage 3 window.onload = function() { 4 document.cookie = "userCode=291382190"; 5 document.cookie = "id=007"; 6 var obj = { 7 name: ‘黄‘, 8 age: 30, 9 sex: 1 10 } 11 var str = JSON.stringify(obj); 12 var oString = JSON.parse(str); 13 //增加 14 var oBtn = document.getElementById(‘btn‘); 15 oBtn.onclick = function() { 16 17 //增 18 localStorage.setItem("password1", "1234"); //方法一,键值对 19 localStorage.setItem("password2", "14"); 20 localStorage.setItem("password3", "132434"); 21 localStorage.goods = "苹果"; //方法二,给键赋值 22 23 sessionStorage.setItem("inpu", "qwe"); 24 sessionStorage.apple = "水果"; 25 } 26 //删除 27 localStorage.removeItem("key"); 28 localStorage.clear(); 29 sessionStorage.removeItem("key"); 30 sessionStorage.clear(); 31 //查 32 //与增加属性一样 33 //查 34 var oShow = document.getElementById(‘show‘); 35 oShow.onclick = function() { 36 //方法一,for 37 var m = localStorage.length; 38 for(var i = 0; i < m; i++) { 39 var key = localStorage.key(i); 40 var value = localStorage.getItem(key); 41 42 console.log(key + ":" + value); 43 } 44 //方法二,for in localStorage想成一个对象 45 for(key in localStorage) { //定义key 46 var value = localStorage.getItem(key); 47 console.log(key + ":" + value); 48 } 49 } 50 51 }
以上是关于HTML5 本地储存-cookie随堂笔记的主要内容,如果未能解决你的问题,请参考以下文章