天天看點

JavaScript 操作 Cookie

//目前b/s程式開發及應用過程中,cookie應用相當頻繁

//如:使用者登陸 ,儲存使用者偏好設定 等等

//下面的類為方面操作cookie提供了幫助

//date:2008/4/24 by danxinju

var Cookie = new Object(); //定義Cookie對象

Cookie.setCookie = function(name/*cookie鍵*/, value/*鍵值*/, option/*選項:過期設定*/){ //設定cookie

var str = name +'='+ escape(value);

if(option){

if(option.expireHours){

var d=new Date();

d.setTime(d.getTime()+option.expireHours*3600*1000);

str += '; expires='+d.toGMTString();

}

if(option.path) str += '; path='+option.path;

if(option.domain) str += '; domain='+option.domain;

if(option.secure) str += '; true';

document.cookie = str;

};

Cookie.getCookie = function(name/*cookie鍵*/){ //擷取一個cookie值

var arr = document.cookie.split('; ');

if(arr.length == 0) return '';

for(var i=0; i

tmp = arr[i].split('=');

if(tmp[0] == name) return unescape(tmp[1]);

return '';

Cookie.delCookie = function(name/*cookie鍵*/){ //删除一個cookie

this.setCookie(name,'',{expireHours:-1});

Cookie.length = function(){ //擷取cookie個數

return document.cookie.split('; ').length;

/**How to use it

Cookie.setCookie('own','this is cookie test!');

alert(Cookie.getCookie('own'));

Cookie.delCookie('own');

**/;>

繼續閱讀