简单的购物车cookie.js封装

简单的购物车cookie.js封装

废话不多说,直接上代码

//创建cookie
function createCookie(key,value,expires){
	//主键值对 key=value
	var cookieText = encodeURIComponent(key) + '=' + encodeURIComponent(value) + ';path=/';
	//判断是否传递了expires参数
	//判断是否传递了下正确的数字
	if(typeof expires === 'number' && !(NaN)){
		var date = new Date();
		date.setDate(date.getDate() + expires);
		cookieText += ';expires=' + date;
	}
	document.cookie = cookieText;
}

//获取cookie
//%E5%A7%93%E5%90%8D=%E5%BC%A0%E5%BF%97%E6%9E%97; url=www.1000phone.com; email=zhangzhilin%401000phone.net
/*
	substring(start,end)
	substr(start,length)
	slice(start,end)
	indexOf()
			start      end
	姓名 :    0		  46
	url :     48      69
	email :   71      104
*/
/*
function $cookie(key){
	var cookieKey = encodeURIComponent(key) + '=';
	var start = document.cookie.indexOf(cookieKey);
	if(start !== -1){
		var end = document.cookie.indexOf(';',start);
		if(end === -1){
			end = document.cookie.length;
		}
		return decodeURIComponent(document.cookie.substring(start + cookieKey.length,end));
	}
	return '没有您要找的数据!';
}
*/
//%E5%A7%93%E5%90%8D=%E5%BC%A0%E5%BF%97%E6%9E%97; url=www.1000phone.com; email=zhangzhilin%401000phone.net
/*
	[
		'%E5%A7%93%E5%90%8D=%E5%BC%A0%E5%BF%97%E6%9E%97',
		'url=www.1000phone.com',
		'email=zhangzhilin%401000phone.net'
	]
	
	[
		[
			'%E5%A7%93%E5%90%8D',
			'%E5%BC%A0%E5%BF%97%E6%9E%97'
		],
		[
			'url',
			'www.1000phone.com'
		],
		[
			'email',
			'zhangzhilin%401000phone.net'
		]
	]
*/
function getCookie(key){
	var arr = document.cookie.split('; ');
	for(var i = 0,len = arr.length;i < len;i ++){
		var list = arr[i].split('=');
		if(encodeURIComponent(key) === list[0]){
			return decodeURIComponent(list[1]);
		}
	}
}
//删除cookie
function removeCookie(key){
	document.cookie = encodeURIComponent(key) + '=;path=/;expires=' + new Date(0);
}

猜你喜欢

转载自blog.csdn.net/yushiyzz/article/details/87910887
今日推荐