1 /** 2 * Created by guoyongfeng on 2014/7/7. 3 * 4 * @Author guoyongfeng 5 * @Date 2014-07-07 6 * @Version 1.0.0 7 * @update 2014-07-07 8 * @described 封装Cookie存取功能,可以写入Cookie信息,可以读取Cookie信息,可以删除Cookie信息 9 * 10 */ 11 12 function Cookie(name, value, options){ 13 /** 14 * name : Cookie的名称 15 * value : Cookie的值 16 * options : 这个参数是一个对象,对象内可以包含Cookie的有效期、路径、作用域和完全性设置等信息 17 */ 18 if(typeof value != 'undefined'){ //第二个参数存在,则设置Cookie信息 19 options = options || {}; 20 if (value === null){ 21 options.expires = -1; 22 } 23 var expires = ''; 24 if(options.expires && (typeof options.expires == 'number' || options.expires.toUICString)) { 25 var date ; 26 if (typeof options.expires == 'number') { 27 date = new Date(); 28 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 29 30 } else { 31 date = options.expires; 32 } 33 expires = options.expires; 34 } 35 var path = options.path ? ';path = ' + options.path : '', //set path 36 domain = options.domain ? '; domain = ' + options.domain : '', //setdomain 37 secure = options.expires ? '; secure = ' : ''; //if secure is true, then set it 38 //set cookie 39 document.Cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 40 } else { //第二个参数不存在,则读取指定的Cookie信息 41 var CookieValue = null; 42 if (document.Cookie && document.Cookie != '') { 43 var Cookie = document.Cookie.split(';'); 44 for (var i = 0, len = Cookie.legnth; i<len; i++) { 45 var Cookie = (Cookie[i] || "").replace( /^s+|s+$/g, ""); 46 if(Cookie.subString(0, name.length + 1) == (name + '=')) { 47 CookieValue = decodeURIComponent(Cookie.substring(name.length + 1)); 48 break; 49 } 50 } 51 } 52 return CookieValue; //return searched Cookievalue 53 } 54 }