最强javascript操作cookie组件

/**
 * @author wsf
 */

var jCookies = (function (){
	var instance;//对象引用
	
	var methods = {
		/**
		 * 设置cookie
		 */
		setCookie : function (cName,cValue,cExpir){
			if(cName){
				var d = new Date();
				if(cExpir)
				  d.setTime(getNowDateTime()+getSpecificDate(cExpir));
				else
				  d = this.expirDate;
			    this.doc.cookie = cName + "="+ escape (cValue) + ";expires=" + d.toGMTString();
			}
		},
		/**
		 * 获得指定cookei
		 */
		getCookie : function (cName){
			var arr,reg=new RegExp("(^| )"+cName+"=([^;]*)(;|$)");
		    if(arr=this.doc.cookie.match(reg))
		        return (arr[2]);
		    else
		        return null;
		},
		/**
		 * 移除cookie
		 */
		removeCookie : function (cName){
			var exp = new Date();
		    exp.setTime(getNowDateTime() - 1);//当前日期-1
		    var cval=this.getCookie(cName);
		    if(cval!=null)
		        this.doc.cookie= cName + "="+cval+";expires="+exp.toGMTString();
		},
		/**
		 * 更改cookie的失效时间
		 */
		updateCookie : function (cName,cValue,cExpir){
			this.setCookie(cName,cValue,cExpir);
		},
		
		/**
		 * 清空所有cookies
		 */
		
		clearCookies : function () {
			var keys = this.doc.cookie.match(/[^ =;]+(?=\=)/g);
			if (keys) {
				for (var i = keys.length; i--; )
				   this.removeCookie(keys[i]);
			}
		}

		
	};
	/**
	 * 创建cookies对象
     * @param {Object} options
	 */
	function singletenCookie(options){
		var options = options || {};
		var expirDateTime = getNowDateTime() + (options.expirDate * 24 * 3600 * 1000 || 24 * 3600 * 1000);//cookie的默认失效时间  单位为天
		var expirD = new Date();
		expirD.setTime(expirDateTime);
		this.expirDate = expirD;
		this.doc = document;//文档对象,操作cookies
		extend(this,methods);
		return this;
	}
	/**
	 * 获取当前时间,单位为毫秒
	 */
	function getNowDateTime(){
		var d = new Date();
		return d.getTime();
	}
	
	/**
	 * 暂时没用默认失效时间单位为天
	 * 获得指定的失效时间
	 * s是代表秒:20s指20秒
	 * h是指小时,如12小时则是:12h
     * d是天数,30天则:30d
	 */
	
	function getSpecificDate(str) {
		var str1 = str.substring(str.length-1) * 1;//字符串转数字
		var str2 = str.replace(str1,"");
		if (str2 == "s") {
			return str1 * 1000;
		} else if (str2 == "h") {
			return str1 * 60 * 60 * 1000;
		} else if (str2 == "d") {
			return str1 * 24 * 60 * 60 * 1000;
		}
	}

	
	/**
	 * 类似继承方法
	 * @param {Object} destination
	 * @param {Object} source
	 */
	function extend(destination, source) {
	    for (var property in source)
	      destination[property] = source[property];
	    return destination;
	}
	
	var _static = {
		name : "jCookies",
		getInstance : function (options){
			if(!instance)
			   instance = new singletenCookie(options);
			return instance;
		}
	}
	return _static;
})();



调用方式
           alert(document.cookie);
           var cookies = jCookies.getInstance();
	    cookies.setCookie("test","123","1s");
	   alert(cookies.getCookie("test"));
	    //cookies.clearCookies();
	    alert(document.cookie);

 

你可能感兴趣的:(JavaScript)