封装操纵cookie的要领

运用原生要领对cookie操纵是有些贫苦的,我们能够将其封装起来,name代表键名,value代表值,不填则为读取名为name的值,option代表设置值若有效期等。个中有效期单元为天。

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天
    原文作者:hover_lew
    原文地址: https://segmentfault.com/a/1190000007209868
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞