JS对cookies、localStorage、sessionStorage三种数据操作例子;
<script type="application/x-javascript"> function c(str) { console.log(str); } var doc = document; var button = document.getElementById("button"); button.addEventListener("click",function(){ test1(); test2(); test3(); },false) function test1(){ cookieUtils.set("name","a001"); cookieUtils.set("pwd","123456"); cookieUtils.set("age","23"); c(cookieUtils.get("pwd")); // c(cookieUtils.del("pwd")); c(doc.cookie); } function test2(){ sessionStorageUtils.set("name","a001"); sessionStorageUtils.set("pwd","123456"); sessionStorageUtils.set("age","23"); c(sessionStorageUtils.get("name")) c(sessionStorageUtils.get("pwd")) c(sessionStorageUtils.get("age")) //c(sessionStorageUtils.del("age")) c(sessionStorageUtils.get("age")) } function test3(){ localStorageUtils.set("name","a001"); localStorageUtils.set("pwd","123456"); localStorageUtils.set("age","23"); c(localStorageUtils.get("name")) c(localStorageUtils.get("pwd")) c(localStorageUtils.get("age")) //c(localStorageUtils.del("age")) c(localStorageUtils.get("age")) } var cookieUtils = { set:function(name,value,expires,path,domain,secure){ if(name.length <= 0){ alert("至少需要指定一个名字"); return false; } var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value); if(expires instanceof Date){ cookieText += "; expires=" + expires.toUTCString(); } if(path){ cookieText += "; path="+path; } if(domain){ cookieText +="; domain="+domain; } if(secure){ cookieText +="; "+secure; } document.cookie = cookieText; return true; }, get:function(name){ var cookieText = encodeURIComponent(name) + "="; var cookieValue = ""; var start = document.cookie.indexOf(cookieText); if(start > -1){ var end = document.cookie.indexOf(";",start); if(end == -1){ end = document.cookie.length; } cookieValue = encodeURIComponent(document.cookie.substring(start + cookieText.length,end)); } return cookieValue; }, del:function(name){ this.set(name,"",new Date(0)); } } var sessionStorageUtils = { set:function(name,value){ if(name.length <= 0){ alert("至少需要指定一个名字"); return false; } sessionStorage.setItem(name,value); return true; }, get:function(name){ return sessionStorage.getItem(name); }, del:function(name){ sessionStorage.removeItem(name); return true; } } var localStorageUtils = { set:function(name,value){ if(name.length <= 0){ alert("至少需要指定一个名字"); return false; } localStorage.setItem(name,value); return true; }, get:function(name){ return localStorage.getItem(name); }, del:function(name){ localStorage.removeItem(name); return true; } } </script>