Javascript操作Cookie

很多情况下我们会需要将一些数据保存在本地,节省资源和获取更好的用户体验,比如购物车数据,用户登录信息之类的,对于保存这些数据cookie无疑是首选,那么如何使用cookie保存和获取这些数据呢?

下面列举了几个常用的cookie操作方法:

设置cookie:

function setCookie(name,value,days,path){
	var t = new Date(),
		  sCookie= name + "=" + escape(value);
		  t.setTime(t.getTime()+days*24*3600*1000);
		 sCookie += ";expires="+t.toGMTString();
	if(path){
		sCookie += ";path="+path;
	}
	document.cookie = sCookie;
}

获取cookie值:

function getCookie(name){
	var preg = new RegExp("(^| )"+name+"=([^;]*)(;|$)","g");
	if(preg.test(document.cookie)){
		return RegExp.$2;
	}else{
		return "";
	}
}

删除cookie:

function delCookie(name){
	setCookie(name,"",-1);
}

清空cookie:

function clearCookie(){
	var cookieArr = document.cookie.split(";");
	for(var i=0;i<cookieArr.length;i++){
		var preg = /([^;]*)=([^;]*)/;
		var match = preg.exec(document.cookie);
		delCookie(match[1]);
	}
}

简单的封装:

var cookie = {
	set : function(name,value,days,path){
		var t = new Date(),
            sCookie= name + "=" + escape(value);
            t.setTime(t.getTime()+days*24*3600*1000);
            sCookie += ";expires="+t.toGMTString();
        sCookie += path && ";path="+path || "";
        document.cookie = sCookie;
	},
	get : function(name){
		var preg = new RegExp("(^| )"+name+"=([^;]*)(;|$)","g");
		return preg.test(document.cookie) && RegExp.$2 || "";
	},
	del : function(name){
		cookie.set(name,"",-1);
	},
	cls : function(){
		var cookieArr = document.cookie.split(";");
        for(var i=0;i<cookieArr.length;i++){
                cookie.del(/([^;]*)=([^;]*)/.exec(document.cookie)[1]);
        }
	}
}

  • 支付宝二维码 支付宝
  • 微信二维码 微信

本文地址: /js-cookie.html

版权声明: 本文为原创文章,版权归 逐梦个人博客 所有,欢迎分享本文,转载请保留出处!

相关文章