首页 > WEB前端 > JavaScript > JavaScript操作Cookie的函数汇总
2015
01-09

JavaScript操作Cookie的函数汇总

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// get cookie with name or undefined if no name
// 根据名称获取Cookie的值
function getCookie(name) {
	var matches = document.cookie.match(new RegExp("(?:^|; )"
			+ name.replace(/([\.$?*|{}\(\)\[\]\\\/\+\^])/g, '\\$1')
			+ "=([^;]*)"));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}
 
// 设置Cookie的值
// set cookie with name and value
// options - object with cookie params (expires, path, domain, secure)
function setCookie(name, value, options) {
	options = options || {};
 
	var expires = options.expires;
 
	if (typeof expires == "number" && expires) {
		var d = new Date();
		d.setTime(d.getTime() + expires * 1000);
		expires = options.expires = d;
	}
	if (expires && expires.toUTCString) {
		options.expires = expires.toUTCString();
	}
 
	value = encodeURIComponent(value);
 
	var updatedCookie = name + "=" + value;
 
	for ( var propName in options) {
		updatedCookie += "; " + propName;
		var propValue = options[propName];
		if (propValue !== true) {
			updatedCookie += "=" + propValue;
		}
	}
 
	document.cookie = updatedCookie;
}
 
// 删除Cookie的值
// remove cookie with name
function deleteCookie(name) {
	setCookie(name, "", {
		expires : -1
	});
}
最后编辑:
作者:郑 国华
这个作者貌似有点懒,什么都没有留下。

留下一个回复