JS cookie封装

2017-01-10 10:03:08来源:segmentfault作者:小脑fu人点击


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<style>
#cas{
display: block;
border:1px solid;
margin:auto;
}
</style>
<title>操控字体的数据</title>
</head>
<body>
<div >
<img src="/photos/touxiang.jpg" />
<img id='hgk' src="/photos/canvas.png" />
</div>
<script>
var Ecookie=function(){
this.doc=document;
}
Ecookie.prototype={
constructor:Ecookie,
set:function(name,val,day){
var name=encodeURIComponent(name),
val=encodeURIComponent(val),
Days = day,
exp = new Date();
if(Days==-1){
exp.setTime(new Date(0));
}else{
exp.setTime(exp.getTime() + Days*24*60*60*1000);
}
console.log(exp.toGMTString());
this.doc.cookie = name + "="+ val + ";expires=" + exp.toGMTString();
},
get:function(name){
var name=encodeURIComponent(name)+"=",
start=this.doc.cookie.indexOf(name),
cookieVal=null;
if(start>-1){
var end=this.doc.cookie.indexOf(";",start);
if(end==-1){
end=this.doc.cookie.length;
}
cookieVal=decodeURIComponent(this.doc.cookie.substring(start+name.length,end))
}
return cookieVal;},
del:function(name){
this.set(name,'',-1)
}
}
var ecookie=new Ecookie();
ecookie.set('name','小寒',7);
// ecookie.del('name');
console.log(ecookie.get('name'));
</script>
</body>
</html>

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台