首页 > 代码库 > HTML5 本地储存-cookie随堂笔记
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: 110 }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 //方法一,for37 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) { //定义key46 var value = localStorage.getItem(key);47 console.log(key + ":" + value);48 }49 }50 51 }
HTML5 本地储存-cookie随堂笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。