首页 > web前端 > js教程 > JavaScript操作cookie类实例_javascript技巧

JavaScript操作cookie类实例_javascript技巧

WBOY
发布: 2016-05-16 16:06:51
原创
1019 人浏览过

本文实例讲述了JavaScript操作cookie类。分享给大家供大家参考。具体如下:

用法:

一、设置cookie

var cookie = new JSCookie();
// 普通设置
cookie .SetCookie("key1","val1");
// 过期时间为一年
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie .SetCookie("key2","val2",expire_time);
// 设置域及路径,带过期时间
cookie .SetCookie("key3","val3",expire_time,".cnblogs.com","/");
// 设置带子键的cookie,子键分别是k1,k2,k3
cookie .SetCookie("key4","k1=1&k2=2&k3=3");
登录后复制

二、读取cookie

// 简单获取
cookie .GetCookie("key1");
cookie .GetCookie("key2");
cookie .GetCookie("key3");
cookie .GetCookie("key4");
// 获取key4的子键k1值
cookie .GetChild("key4","k1");
登录后复制

三、删除

cookie .Expire("key1");
cookie .Expire("key2");
cookie .Expire("key3");
cookie .Expire("key4");
登录后复制

示例:

<script type="text/javascript">
 String.prototype.Trim = function()
 {
   return this.replace(/^\s+/g,"").replace(/\s+$/g,"");
 }
 function JSCookie()
 {
   this.GetCookie = function(key)
   {
     var cookie = document.cookie;
     var cookieArray = cookie.split(';');
     var getvalue = "";
     for(var i = 0;i<cookieArray.length;i++)
     {
       if(cookieArray[i].Trim().substr(0,key.length) == key)
       {
         getvalue = cookieArray[i].Trim().substr(key.length + 1);
         break;
       }
     }
     return getvalue;
   };
   this.GetChild = function(cookiekey,childkey)
   {
     var child = this.GetCookie(cookiekey);
     var childs = child.split('&');
     var getvalue = "";
     for(var i = 0;i < childs.length;i++)
     {
       if(childs[i].Trim().substr(0,childkey.length) == childkey)
       {
         getvalue = childs[i].Trim().substr(childkey.length + 1);
         break;
       }
     }
     return getvalue;
   };
   this.SetCookie = function(key,value,expire,domain,path)
   {
     var cookie = "";
     if(key != null && value != null)
       cookie += key + "=" + value + ";";
     if(expire != null)
       cookie += "expires=" + expire.toGMTString() + ";";
     if(domain != null)
       cookie += "domain=" + domain + ";";
     if(path != null)
       cookie += "path=" + path + ";";
     document.cookie = cookie;
   };
   this.Expire = function(key)
   {
     expire_time = new Date();
     expire_time.setFullYear(expire_time.getFullYear() - 1);
     var cookie = " " + key + "=e;expires=" + expire_time + ";"
     document.cookie = cookie;
   }
 }
</script>
登录后复制

至此完毕.

希望本文所述对大家的javascript程序设计有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板