Fork me on GitHub

js简单操作Cookie

  贴一段js简单操作Cookie的代码:

 1 //获取指定名称的cookie的值
 2 function getCookie(objName) {
 3     var arrStr = document.cookie.split("; ");
 4     for (var i = 0; i < arrStr.length; i++) {
 5         var temp = arrStr[i].split("=");
 6         if (temp[0] == objName) return unescape(temp[1]);
 7     }
 8 }
 9 //添加cookie
10 function addCookie(objName, objValue, objHours) {      
11     var str = objName + "=" + escape(objValue);
12     if (objHours > 0) {                               //为时不设定过期时间,浏览器关闭时cookie自动消失
13         var date = new Date();
14         var ms = objHours * 3600 * 1000;
15         date.setTime(date.getTime() + ms);
16         str += "; expires=" + date.toGMTString();
17     }
18     document.cookie = str;
19 }
20 //删除cookie
21 function delCookie(name)
22 {
23     document.cookie = name + "=;expires=" + (new Date(0)).toGMTString();
24 }
posted @ 2014-03-19 13:42  田园里的蟋蟀  阅读(1015)  评论(0编辑  收藏  举报