Home >Web Front-end >JS Tutorial >js operation cookie example
This article mainly shares with you js cookie operation examples, mainly in the form of code, hoping to help everyone.
/** * * @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<len;i++){ if(keys[i] === key){ keys.splice(i,1); break; } } this.length--; //最重要通过该cookie值设置为空字符串以及将有效期设置为0来删除指定的cookie document.cookie = key + "=;max-age=0"; }; //删除所有的cookie this.clear = function(){ for(var i = 0,len = keys.length;i<len;i++){ document.cookie = keys[i] + "=;max-age=0"; } //重置所有的内部状态 cookie = {}; keys = []; this.length = 0; } }
Related recommendations:
Principle and phenomenon analysis of cookies
Detailed explanation of cookies for PHP session control
Detailed explanation of cookie usage
The above is the detailed content of js operation cookie example. For more information, please follow other related articles on the PHP Chinese website!