<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JS操作cookie.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="JSCookies.js"></script>
` <script type="text/javascript">
//用法:
//一、设置cookie
var cookie = new Cookies();
function set() {
//普通设置
cookie.set("key1", "哈哈3");
//过期时间为一年
var d = new Date();
d.setFullYear(d.getFullYear() + 1);
cookie.set("key2", "val2", d);
//设置域及路径,带过期时间
cookie.set("key3", "val3", d, "casett", "/");
//设置带子键的cookie,子键分别是k1,k2,k3
cookie.set("key4", "k1=哈哈是&k2=2&k3=3");
};
//二、读取cookie
//简单获取
function get() {
alert(cookie.get("key1"));
alert(cookie.get("key2"));
alert(cookie.get("key3"));
alert(cookie.get("key4"));
//获取key4的子键k1值
alert(cookie.getChild("key4","k1"));
alert(cookie.getChild("key4","k2"));
}
//三、删除
function remove() {
cookie.remove("key1");
cookie.remove("key2");
cookie.remove("key3");
cookie.remove("key4");
}
</script>
</head>
<body>
<input type="button" value="set" οnclick="set()"/>
<input type="button" value="get" οnclick="get()"/>
<input type="button" value="clear" οnclick="remove()"/>
</body>
</html>
JSCookies js
String.prototype.Trim = function() {
return this.replace(/^/s+/g, "").replace(//s+$/g, "");
}
function Cookies() {
this.get = function(key) {
var cookie = document.cookie;
var cookieArray = cookie.split(';');
var val = "";
for (var i = 0; i < cookieArray.length; i++) {
if (cookieArray[i].Trim().substr(0, key.length) == key) {
val = cookieArray[i].Trim().substr(key.length + 1);
break;
}
}
return unescape(val);
};
this.getChild = function(key, childKey) {
var child = this.get(key);
var childs = child.split('&');
var val = "";
for (var i = 0; i < childs.length; i++) {
if (childs[i].Trim().substr(0, childKey.length) == childKey) {
val = childs[i].Trim().substr(childKey.length + 1);
break;
}
}
return val;
};
this.set = function(key, value) {
var cookie = "";
if (!!key && !!value)
cookie += key + "=" + escape(value) + ";";
if (!!arguments[2])
cookie += "expires=" + arguments[2].toGMTString() + ";";
if (!!arguments[3])
cookie += "domain=" + arguments[3] + ";";
if (!!arguments[4])
cookie += "path=" + arguments[4] + ";";
document.cookie = cookie;
};
this.remove = function(key) {
var date = new Date();
date.setFullYear(date.getFullYear() - 1);
var cookie = " " + key + "=;expires=" + date + ";"
document.cookie = cookie;
}
}