Cookie:
1 //setCookie 2 3 function setCookie(name,value){ 4 5 var Days = 30; 6 7 var exp = new Date(); 8 9 exp.setTime(exp.getTime() + Days*24*60*60*1000); 10 11 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 12 13 } 14 //getCookie 15 16 function getCookie(name){ 17 18 var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); 19 20 if(arr=document.cookie.match(reg)) 21 22 return unescape(arr[2]); 23 24 else 25 26 return null; 27 28 } 29 //delCookie 30 31 function delCookie(name){ 32 33 var exp = new Date(); 34 35 exp.setTime(exp.getTime() - 1); 36 37 var cval=getCookie(name); 38 39 if(cval!=null) 40 41 document.cookie= name + "="+cval+";expires="+exp.toGMTString(); 42 43 } 44 45 //如果需要设定自定义过期时间 46 function setCookie(name,value,time){ 47 48 var strsec = getsec(time); 49 50 var exp = new Date(); 51 52 exp.setTime(exp.getTime() + strsec*1); 53 54 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 55 56 } 57 58 function getsec(str){ 59 60 var str1=str.substring(1,str.length)*1; 61 62 var str2=str.substring(0,1); 63 64 if (str2=="s"){ 65 66 return str1*1000; 67 68 } else if (str2=="h"){ 69 70 return str1*60*60*1000; 71 72 } else if (str2=="d"){ 73 74 return str1*24*60*60*1000; 75 76 } 77 } 78 79 //这是有设定过期时间的使用示例: 80 //s20是代表20秒 81 //h是指小时,如12小时则是:h12 82 //d是天数,30天则:d30
LocalStorge:
1 if(window.localStorage){ 2 console.log("浏览器支持localStorage"); 3 4 }else{ 5 console.log("浏览器支持localStorage"); 6 } 7 //JS下的操作方法 8 9 //获取键值:localStorage.getItem(“key”) 10 //设置键值:localStorage.setItem(“key”,”value”) 11 //清除键值:localStorage.removeItem(“key”) 12 //清除所有键值:localStorage.clear() 13 //获取键值2:localStorage.keyName 14 //设置键值2:localStorage.keyName = “value” 15 //判断 key值是否存在的两种方法 16 //localStorage.keyName === undefined true为key值不存在 false 为key值存在 17 //typeof localStorage.keyName === undefined true为key值不存在 false 为key值存在
SessionStorage:
1 //设置key value sessionStorage.setItem("key", "value") 2 //获取key值 sessionStorage.getItem("key") //value 3 //删除指定key本地存储的值 sessionStorage.removeItem("key") 4 //清除所有的key/value sessionStorage.clear()