您的位置:首页 > Web前端 > JavaScript

Js 操控 Cookie(简单实用)

2016-07-01 15:19 936 查看
使用环境根据自身业务需求而定义!
var Cookies_ = {};


/**

* 设置Cookies_

* @param name 键名

* @param value 键值

*/

Cookies_.sets = function(name, value) {
name = encodeURIComponent(name);
value = encodeURIComponent(value);
var argv = arguments;
var argc = arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : '/';
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
};

/**

* 读取Cookies_

* @param name 键名

* @returns {*}

*/

Cookies_.gets = function(name) {
name = encodeURIComponent(name);
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
var j = 0;
while (i < clen) {
j = i + alen;
if (document.cookie.substring(i, j) == arg)
return decodeURIComponent(Cookies_.getsCookieVals(j));
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
break;
}
return null;
};

/**

* 清除Cookies_

* @param name 键名

*/

Cookies_.clears = function(name) {
if (Cookies_.gets(name)) {
var expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
Cookies_.sets(name, "", expdate);
}
};

Cookies_.getsCookieVals = function(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
};

 

注意:容易出现的问题

Cookie 限制个数 (根据浏览器而定)

Cookie 作用域

右键链接另存为附件 CookieManage.js

对于上述问题 可以使用html5 localStorage & sessionStorage 进行优化

参考链接http://dream128.cn/index.php?m=Article&a=detail&id=7




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  需求 javascript cookie