欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS Cookies的设置 读取 删除

程序员文章站 2022-07-05 23:43:30
...
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JS Cookies的设置 读取 删除</title>
</head>
<body>
<script type="text/javascript">
//设置cookies 
function setCookie(name,value){ 
    var Days = 30; 
    var exp = new Date(); 
    exp.setTime(exp.getTime() + Days*24*60*60*1000); 
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
}

//读取cookies 
function getCookie(name){ 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]); 
    else 
        return null; 
} 

//删除cookies 
function delCookie(name){ 
    var exp = new Date(); 
    exp.setTime(exp.getTime() - 1); 
    var cval=getCookie(name); 
    if(cval!=null) 
        document.cookie= name + "="+cval+";expires="+exp.toGMTString(); 
} 
//使用示例 
setCookie("website","onestopweb.iteye.com"); 
alert(getCookie("website")); 
//delCookie("website");
</script>
</body>
</html>

 

效果图:
JS Cookies的设置 读取 删除
            
    
    博客分类: 境-JS 设置Cookie读取Cookie删除CookieCookie操作JS Cookie 
 

 封装上面的方法:

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JS Cookies的设置 读取 删除</title>
</head>
<body>
<script type="text/javascript">
var cookie = {
    set:function(name,value){
    	var Days = 30; 
        var exp = new Date(); 
        exp.setTime(exp.getTime() + Days*24*60*60*1000); 
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
    },
    get:function(name){
    	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]); 
        else 
            return null; 
    },
	delete:function(name){
		var exp = new Date(); 
	    exp.setTime(exp.getTime() - 1); 
	    var cval=cookie.get(name);
	    if(cval!=null){
	    	document.cookie= name + "="+cval+";expires="+exp.toGMTString();
	    }  
    }
}
cookie.set("user","chaoyi2");//设置为24天过期
alert(cookie.get("user"));//获取cookie
//cookie.delete("user");
</script>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

  • JS Cookies的设置 读取 删除
            
    
    博客分类: 境-JS 设置Cookie读取Cookie删除CookieCookie操作JS Cookie 
  • 大小: 43.6 KB