一:操作
1.得到某个cookie的值
function getCookie(name){
var start = document.cookie.indexOf(name+"=");
var len = start+name.length+1;
if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
if (start == -1) return null;
var end = document.cookie.indexOf(";",len);
if (end == -1) end = document.cookie.length;
return decodeURIComponent(document.cookie.substring(len,end));
}
2.
设置cookie的值
1. function setCookie(name,value,expires,path,domain,secure){
2. var today = new Date();
3. today.setTime(today.getTime());
4. if(expires)
5. {
6. expires = expires * 1000 * 60 * 60 *24;
7. }
8. var expires_date = new Date(today.getTime() + (expires));
9. value = encodeURIComponent(unescape(value));
10. document.cookie = name+'='+value+
11. ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
12. ( ( path ) ? ';path=' + path : '' ) +
13. ( ( domain ) ? ';domain=' + domain : '' ) +
14. ( ( secure ) ? ';secure' : '' );
15. }
3.删除cookie的值
1. function delAllCookie()
2. {
3. tmpArr = document.cookie.split(";");
4. delKey = new Array();
5. for(i in tmpArr)
6. {
7. if(tmpArr[i].indexOf("mykeywords") != -1)
8. {
9. delKey.push(decodeURIComponent(tmpArr[i].split("=")[0]));
10. }
11. }
12. today = new Date();
13. today.setTime(today.getTime() - 10000);
14. for(i in delKey)
15. {
16. name = delKey[i];
17. document.cookie = name+"='';expires="+today.toGMTString();
18. }
19. tmpArr = delKey = today = "";
20. }
由于JS上无法直接删除cookie所以采用过期的方式来删除cookie上边的例子是删除多个的,想单独删除某个值的时候参照添加单个 cookie
1. //删除cookie的某个值
2. function delCookie(value)
3. {
4. len = keywords.length;
5. for(i in keywords)
6. {
7. if(keywords[i] == value)
8. {
9. keywords.splice(i,1);
10. }
11. }
12.
13. if(keywords.length == 0)
14. {
15. delAllCookie();
16. }
17. }
decodeURIComponent 对UTF-8的字符进行解码
encodeURIComponent 对字符进行编码 UTF-8
可以用来和UTF-8的程序文件进行交互
JS操作cookie的BUG
当不同级目录设置操作cookie的时候,下级目录可以读取上级目录,但是不能对上级目录设置的COOKIE进行直接操作,如果对数组类型的 cookie进行操作时,下级目录会自动复制上级目录中的cookie导致cookie会现问题(会出现两个一样的cookie),所以在不同级目录中最好不要操作数同一个组类型的cookie
二:属性
Domain 属性:获取或设置 Cookie 对其有效的 URI。
Expires 属性:获取或设置作为 DateTime 的 Cookie 过期日期和时间。
Value 属性:获取或设置 Cookie 的 Value。