標籤:
一、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隨堂筆記