444   jQuery JS

网上提供的js-cookie的过期时间大部分是天,比如GitHub上的jquery-cookiejs-cookie

但是业务需求过期时间是秒内的,比如10秒内点击按钮次数不能超过10次,只要自己手动写了个简单的js-cookie

var cookie = {
	set:function(name,value,second){  
		var d = new Date();
		// 设置cookie过期时间,getTime获得是毫秒
		d.setTime(d.getTime() + second*1000);
		// escape(value)转码,避免乱码
		document.cookie = name + '=' + escape(value) + '; expires=' + d.toGMTString();
	},
	get:function(name){  
		// document.cookie保存格式为:document.cookie = 'user=test; click_times=10;';
		if (document.cookie.length>0){
			var c_start=document.cookie.indexOf(name + "=")
			if (c_start!=-1){ 
				c_start=c_start + name.length+1 
				var c_end=document.cookie.indexOf(";",c_start)
				if (c_end==-1){
					c_end=document.cookie.length;
				} 
				return unescape(document.cookie.substring(c_start,c_end))
					
			} 
		}

		return '';
	},
	del:function(name){
		var d = new Date();
		d.setTime(d.getTime());
		// 将cookie设置为空,过期时间为当前,即可删除cookie
		document.cookie = name + '=; expires=' + d.toGMTString();
	}                               
};



Leave a Reply

Your email address will not be published. Required fields are marked *