封裝操做cookie的方法

使用原生方法對cookie操做是有些麻煩的,咱們能夠將其封裝起來,name表明鍵名,value表明值,不填則爲讀取名爲name的值,option表明設置值若有效期等。其中有效期單位爲天。cookie

function cookie(name, value, options) {
        if (typeof value != 'undefined') {
            options = options || {};
            //若是值爲null, 刪除cookie
            if (value === null) {
                value = '';
                options = {
                    expires: -1
                };
            }
            //設置有效期
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = ';expires=' + date.toGMTString();
            }
            var path = options.path ? ';path=' + (options.path) : '';
            var domain = options.domain ? ';domain=' + (options.domain) : '';
            var secure = options.secure ? ';secure' : '';
            //設置cookie
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            //讀取cookie
            if (document.cookie.length > 0) {
                var start = document.cookie.indexOf(name + "=")
                if (start != -1) {
                    start = start + name.length + 1;
                    var end = document.cookie.indexOf(";", start);
                    if (end == -1){
                        end = document.cookie.length;
                    }
                    return decodeURIComponent(document.cookie.substring(start, end));
                }
            }
            return ""
        }
    }

    cookie("name", "zhangsan"); //添加name=zhangsan
    cookie("name", null); // 刪除name
    cookie("age", "10", {
        expires: 30
    }); // 添加age=10且有效期30天
相關文章
相關標籤/搜索