首页 > 代码库 > JS设置cookie,删除cookie

JS设置cookie,删除cookie

js设置cookie有很多种方法。

第一种:(这个是w3c官网的代码)

<script>//设置cookiefunction setCookie(cname, cvalue, exdays) {    var d = new Date();    d.setTime(d.getTime() + (exdays*24*60*60*1000));    var expires = "expires="+d.toUTCString();    document.cookie = cname + "=" + cvalue + "; " + expires;}//获取cookiefunction getCookie(cname) {    var name = cname + "=";    var ca = document.cookie.split(;);    for(var i=0; i<ca.length; i++) {        var c = ca[i];        while (c.charAt(0)== ) c = c.substring(1);        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);    }    return "";}//清除cookie  function clearCookie(name) {      setCookie(name, "", -1);  }  function checkCookie() {    var user = getCookie("username");    if (user != "") {        alert("Welcome again " + user);    } else {        user = prompt("Please enter your name:", "");        if (user != "" && user != null) {            setCookie("username", user, 365);        }    }}checkCookie(); </script>

第二种:

<script>//JS操作cookies方法!//写cookiesfunction setCookie(c_name, value, expiredays){     var exdate=new Date();    exdate.setDate(exdate.getDate() + expiredays);    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());   } //读取cookiesfunction getCookie(name){    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");     if(arr=document.cookie.match(reg))         return (arr[2]);    else        return null;}//删除cookiesfunction 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(username,Darren,30) alert(getCookie("username"));</script>

 

JS设置cookie,删除cookie