JavaScript 操作 Cookie 完整示例:设置、读取与删除
作者:异步漫步时间:2026-10-24 18:30:12浏览:236
本文提供了一套完整的 JavaScript Cookie 操作代码,涵盖读取、设置及删除功能。通过 getCookie、SetCookie 和 DeleteCookie 等函数,演示如何解析 cookie 字符串、处理过期时间与路径参数,并实现简单的成员数据持久化存储示例。
JavaScript 操作 Cookie 完整示例:设置、读取与删除
以下内容整理自一篇国外的技术文章,主要介绍如何使用 JavaScript 处理 Cookie。
参考链接:https://www.jb51.net/article/20553.htm
具体实现代码如下:
var sel = new Object();
var sel_num = 0;
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
//alert(document.cookie.length);
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal(j);
i = document.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
return value;
}
function DeleteCookie(name) {
if (GetCookie(name) != null) {
SetCookie(name, "", null, "/", null);
}
}
function cookie_content() {
i = 0;
var content = "";
for (key in sel) {
if (i == 0) {
content += key + "[" + sel[key] + "]";
}
else {
content += "," + key + "[" + sel[key] + "]";
} i++;
}
return content;
}
function inni_data() {
var cookie_sel = new Object();
cookie_str = GetCookie("Member_COOKIE");
if (cookie_str != "" && cookie_str != null) {
cookie_sel = cookie_str.split(',');
for (var k = 0; k < cookie_sel.length; k++) {
i = cookie_sel[k].indexOf("[");
j = cookie_sel[k].indexOf("]");
sel[cookie_sel[k].substring(0, i)] = cookie_sel[k].substring(i + 1, j);
sel_num++;
}
draw();
}
}
function addMember(id, nm) {
if (!sel[id]) {
sel_num++; sel[id] = nm;
}
else
{sel[id] = nm;}
SetCookie("Member_COOKIE", cookie_content(), null, "/", null);
}
function draw() {
out = '';
for (key in sel) {
$("#"+key).val(sel[key] );
}
} 作者最新文章
D3.js 比例尺与坐标轴的配置详解
2026-11-05 16:54:46
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
