js jquery设置、检测、获取、删除cookie,判断cookie是否存在,cookie插件

我来纠错
/*设置cookie,path:路径,expires:有效天数,domain:cookie的域名*/
xcookie.setCookie('cookieTest', '我是cookie存储的内容', { path: '/',expires:3,domain:'fedrobots.com'});

/*检测、获取cookie*/
var thisCookie = xcookie.getCookie('cookieTest');
if(thisCookie){
	alert(thisCookie);  //如果cookie存在,就会弹出cookie值
}

/*删除cookie 必须要配置和设置cookie一样的path和domain*/
xcookie.deleteCookie('cookieTest', { path: '/',domain:'fedrobots.com'});

/*cookie插件*/
(function (window) {
   window.xcookie = {
        cookie: function (name, value, options) {
            var path = options.path ? '; path=' + (options.path) : '',
                domain = options.domain ? '; domain=' + (options.domain) : '',
                secure = options.secure ? '; secure' : '',
                expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                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.toUTCString();
                
            }
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        },
        setCookie: function (name, value, options) {
            var options = options || {};
            this.cookie(name, value, options);
        },
        getCookie: function (name) {
            var cookieValue = null,
                doc = document;
            if (doc.cookie && doc.cookie != '') {
                var cookies = doc.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = $.trim(cookies[i]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        },
        deleteCookie: function (name, options) {
            var options = options || {},
                value = '';
            options.expires = -1;
            this.cookie(name, value, options);
        }
    }
})(window);

发送
热门关键词:
命令
知识类型:
标题描述:
详细解答:

提交审核您编辑的知识会经过 前端大牛 人工审核。