Javascript Cookie小插件

var ManagerCookie = function(){
    //添加cookie
    function addCookie(key,value,time,path){
        key = encodeURI(key);
        value = encodeURI(value);
        var _expires = new Date();
        time = time ? time : 7;
        _expires.setTime(_expires.getTime() + time*3600*24);
        path = path?path:"/";
        path = ";path="+path;
        var expires = ";expires="+_expires.toUTCString();
        document.cookie = key+"="+value+path+expires;
    };
    //获取cookie
    function getCookie(key){
        var value = "";
        key = encodeURI(key);
        var allCookies = document.cookie;
        key = key + "=";
        var pos = allCookies.indexOf(key);
        if(pos!=-1){
            var start = pos+key.length;
            var end = allCookies.indexOf(";",start);
            //只存在一个cookie
            if(end == -1){
                end = allCookies.length;
            }
            value = allCookies.substring(start,end);
        };
        return decodeURI(value);
    };
    //删除cookie
    function deleteCookie(key,path){
        key = encodeURI(key);
        path = path?path:"/";
        path = ";path="+path;
        var _expires = new Date(0);
        var expires = ";expires="+_expires.toUTCString();
        document.cookie = key + "=" + path +expires;
    }
    return {
        addCookie:addCookie,
        deleteCookie:deleteCookie,
        getCookie:getCookie
    }
    }();

 

posted on 2017-04-20 16:56  菜的黑人牙膏  阅读(176)  评论(0编辑  收藏  举报

导航