日期:2014-05-16  浏览次数:20453 次

javascript操作cookie笔记
	function Cookie(){
		// 保存数据到cookie
		this.put = function (name,value){
			if((""+value).indexOf(";")!=-1){
				document.cookie = name+"="+escape(value.substring(0,value.indexOf(";")))+value.substring(value.indexOf(";"));
			}else{
				document.cookie = name+"="+escape(value);
			}
		};
		// 获取指定名称的cookie值
		this.get = function(name){
			return unescape(this.getAll()[name]);
		};
		// 获取本机所有cookie的集合
		this.getAll = function(){
			var _cache = {};
			var _cs = document.cookie;
			if(_cs){
				var _a = _cs.split("; ");// TODO 未验证各浏览器版本的规则是否一致
				for(var i=0; i<_a.length; i++){
					_cache[_a[i].substring(0,_a[i].indexOf("="))]=unescape(_a[i].substring(_a[i].indexOf("=")+1));
				}
			}
			return _cache;
		};
		// 删除指定名称的cookie
		this.remove = function(name){
			this.setTimeout(name,-1);
		};
		//设置超时时间,单位毫秒
		this.setTimeout = function(name,ms){
			var reg = /(-)?\d*/;
			if(reg.test(ms)){
				var exp = new Date();
				exp.setTime(exp.getTime() + ms);
				this.put(name,this.get(name)+";expires="+exp.toGMTString());
			}
		}
	}
?