js cookie 存储封装

来源:互联网 发布:mac 容器 英文 编辑:程序博客网 时间:2024/05/17 02:30
    <script>        window.onload =function(){            //s 代表秒  h代表小时  d代表天            var demo = '{"product":[' + '{"proId":' + 123 + ',"proPrice":' + 100 + ',"proNum":' + 10 + '}' + '],"totalPrice":' + 100 + '}';            var demo1 = '{"product":[{"proId":123,"proPrice":100,"proNum":10}],"totalPrice":100}';            console.log(demo+"xx");            setCookie("name",demo,"s100");            var value = getCookie("name");            console.log('获取cookie的值为'+value);            var cooieJson = JSON.parse(value);            console.log(cooieJson.product[0].proId+"]]"+cooieJson.product[0].proPrice);        }        //判断是否为最后一个来决定是否要加最后的逗号  ② 讲id 的值前边拼接上 "{"  最后字段的值后边拼接上 } "        '{"product":[{"proId":"123","proPrice":"100"},{},{}]}'        '{"product":[' + "{proId:" + 123 + ",proPrice:" + 100 + ",proNum" + 10 + "}" + '],totalPrice:' + 100 + '}';        //cookie 封装 获取 cookie         function getCookie(name) {         var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");        if(arr=document.cookie.match(reg))        return unescape(arr[2]);         else         return null;         }         //删除cookie        function delCookie(name)         {         var exp = new Date();         exp.setTime(exp.getTime() - 1);         var cval=getCookie(name);         if(cval!=null)         document.cookie= name + "="+cval+";expires="+exp.toGMTString();         }         //设置cookie 以及过期时间        function setCookie(name,value,time)        {             var strsec = getsec(time);             console.log("过期时间为--->"+strsec);            var exp = new Date();             exp.setTime(exp.getTime() + strsec*1);             document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();             }         //获取设置过期时间        function getsec(str)        {            alert(str);            var str1=str.substring(1,str.length)*1;            var str2=str.substring(0,1);            if (str2=="s")           {                 return str1*1000;            }           else if (str2=="h")           {                return str1*60*60*1000;            }           else if (str2=="d")           {                return str1*24*60*60*1000;            }         }     </script>
1 0
原创粉丝点击