兼容cookie和webStorage

html页面  
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/sea.js"></script>
    <script>
        seajs.config({
            alias:{
                cookie:'cookie',
                strong:'strong'
            }
        })
 
        seajs.use("main")
 
    </script>
</head>
<body>
 
</body>
</html>
 
 
 
 
main.js页面
 
define(function(require,exports,module){
    var strong=require("strong");
 
        strong.setItem("hellowords","01-20 16:15",1);
 
        strong.setItem("style","hello",1);
 
        //strong.removeItem('style');
 
        //strong.removeItem("hellowords");
 
        strong.setItem("lili","hello",1);
 
        strong.setItem("z","zz",1);
 
        //strong.removeItem('lili');
 
        strong.setItem('guo','boyu',1);
 
        //strong.getItem("guo")
        console.log(strong.getItem("guo"))
 
})
 
 
strong.js页面
 
define(function(require,exports,module){
    var ls=window.localStorage;
 
    if(!ls){// 如果支持webStorage
        return{
 
            getItem:function(key){
                return ls.getItem(key);
            },
            setItem:function(key,val){
                this.removeItem(key);
                return ls.setItem(key,val);
            },
            removeItem:function(key){
                return ls.removeItem(key);
            }
        }
 
 
    }else{// 支持cookie
        var cookie=require("cookie");
        return{
            getItem:function(key){
                return cookie.getItem(key)
            },
            setItem:function(key,val,days){
                cookie.setItem(key,val,days)
            },
            removeItem:function(key){
                cookie.removeItem(key)
            }
        }
 
    }
 
 
})
 
cookie页面
 
 
define(function(require,exports,module){
 
    return {
 
        getItem:function(key){
            //console.log(key)
            var reg=new RegExp('(^| )'+key+'=([^;]*)(;|$)');
            var arr=document.cookie.match(reg);
            //console.log(arr)
            if(arr) return unescape(arr[2]);
            return null;
        },
        setItem:function(key,val,days){
            //如果不设置天数 , 默认为30天
            days=days?days:30;
            var exp=new Date();
            exp.setTime(exp*1+days*(24*60*60*1000));
            if(typeof(Domain)==="undefined" || Domain==null){
                Domain=location.host // 获取主机地址
            }
            document.cookie=key+'='+escape(val)+';expires='+exp+';domain='+Domain+';path=/';
        },
        removeItem:function(key){
            // 设置时间过期
            if(this.getItem(key)){
                this.setItem(key,"",-1);
            }
        }
 
    }
 
 
 
})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2016-12-20 17:04  *小七儿*  阅读(448)  评论(0编辑  收藏  举报