闫小样丶
技术热情,对技术问题深究的态度,善于总结,喜欢思考解决问题的各种方法和思路,能够自己快速解决各种技术问题。

/**
* cookie中存值
* */
function setCookie (name, value) {
if (value) {
var days = 1; //定义一天
var exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
// 写入Cookie, toGMTString将时间转换成字符串
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
}
};

/**
* cookie中取值
* */
function getCookie (name) {
var arr,reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //匹配字段
if (arr = document.cookie.match(reg)) {
return unescape(arr[2]);
} else {
return null;
}
};

/**
* 清除指定cookie值
* */
function delCookie (name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = setCookie(name);
if (cval && cval != null) {
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
}
};

/**
* 清除全部cookie值
* */

function clearCookie() {
var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
if (keys) {
for (var i = keys.length; i--;) {
// document.cookie = keys[i] +'=0;expires=' + new Date( 0).toUTCString()
document.cookie = keys[i] +'=0;expires=' + new Date( 0).toUTCString() + ";path=/video_learning" + ";domain=localhost";
}
}
};

注意:清除cookie的时候,需要同时删除path和 domain,否则会出现cookie没有被清除的情况出现。

详情链接:https://blog.csdn.net/weixin_38047955/article/details/78832643

 

/**
* cookie中存值
* */
function setCookie(name, value) {
if (value) {
var days = 1; //定义一天
var exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
// 写入Cookie, toGMTString将时间转换成字符串
// document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/video_learning" + ";domain=localhost";
}
};

注意:在cookie中存储时,一定要注意把path改为根路径,并加上domain;否则在其他页面是无法获取到存储的cookie值的。

 

/**
* cookie中存值(存放多长时间)
* */
function setCookie(name, value, expiredays) {
if (value) {
var days = 1; //定义一天
var exp = new Date();
exp.setTime(exp.getTime() + expiredays);
// 写入Cookie, toGMTString将时间转换成字符串
document.cookie = name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exp.toGMTString()) + ";path=/" + ";domain=localhost";
}
};

 

/**
* cookie中获取域名
* */
function GetCookieDomain() {
var host = location.hostname;
var ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
if (ip.test(host) === true || host === 'localhost') return host;
var regex = /([^]*).*/;
var match = host.match(regex);
if (typeof match !== "undefined" && null !== match) host = match[1];
if (typeof host !== "undefined" && null !== host) {
var strAry = host.split(".");
if (strAry.length > 1) {
host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
}
}
return '.' + host;
}

posted on 2019-07-31 10:52  闫小样丶  阅读(12621)  评论(0编辑  收藏  举报