本文主要和大家分享js操作cookie实例,主要以代码的形式和大家分享,希望能帮助到大家。
/**
*
* @param {有效期} maxage
* @param {作用域} path
*/
function cookieStorage(maxage, path) {
var cookie = (function () {
var cookies = {}; //该对象会最终返回
var all = document.cookie; //一大些字符串的形式获取所有cookie信息
if (all === "") {
return cookie; //返回一个空对象
}
var list = all.split(";"); //分离出键值对
for (var i = 0, len = list.length; i < len; i++) {
var cookie = list[i];
var p = cookie.indexOf("="); //查找第一个"="符号
var name = cookie.substring(0, p); //获取cookie名字
var value = cookie.substring(p + 1); //获取cookie对应的值
value = decodeURIComponent(value); //对其值进行解码
cookies[name] = value;
}
return cookies;
}());
//将所有cookie的名字存储到一个数组中
var keys = [];
for (var key in cookie) {
keys.push(key);
}
//现在定义存储api公共的属性和方法
//存储的cookie的个数
this.length = keys.length;
//返回第n个cookie的名字,如果n越界则返回null
this.key = function (n) {
if (n < 0 || n >= keys.length) {
return null;
}
return keys[n];
}
//返回指定名字的cookie值,如果不存在则返回null
this.getItem = function (name) {
return cookie[name] || null;
}
//存储cookie值
this.setItem = function (key, value) {
if (!(key in cookie)) { //如果要存储的cookie还不存在
keys.push(key);
this.length++; //cookie个数加一
}
//将该键值对存储到cookie对象中
cookie[key] = value;
//开始正式设置cookie
//首先将要存储的cookie的值进行编码,同时创建一个“名字=编码后的值”形式的字符串
var cookie = key + "=" + encodeURIComponent(value);
//将cookie的属性也加入到该字符串中
if (maxage) cookie += ";max-age=" + maxage;
if (path) cookie += ";path=" + path;
//通过document.cookie属性来设置cookie
document.cookie = cookie;
};
//删除指定的cookie
this.removeItem = function(key){
if(i(key in cookie)){
return;
}
//从内部维护的cookie组删除指定的cookie
delete cookie[key];
//同时将cookie中的名字也在内部的数组中删除
//如果使用es5定义的数组indexof方法会更简单
for(var i = 0, len = keys.length ; i相关推荐:
台讯电子企业网站管理系统 简繁全功能版
超级适合代理建设企业站点的企业源码,超方面实用!程序说明: 1.特色:简繁中文切换、产品展示系统、新闻发布系统、会员管理系统、留言本计数器、网站信息统计、强大后台操作 功能等; 2.页面包括:首页、企业介绍、滚动公告通知发布系统、企业新闻系统、产品展示系统、企业案例发布展示系 统、企业招聘信息发布系统、信息资源下载系统、在线定单系统、在线客服系统、在线留言本系统、网站调查投票系统、友情连接系统、会
下载









