var d= new Date(); d.setHours(d.getHours() + (24 * 30)); //保存一個月 document.cookie = "visited=yes; expires=" + d.toGMTString(); 這樣你的cookie就能保存一個月了,下面是我測試用的代碼,你本身看看是否有其餘幫助,有的話儘管拿去:
安全
function Window_Load(){
setCookie("name","111"); //臨時cookie
setCookie("age","222",24 * 7); //保存7天
setCookie("address","333",24,"/"); //保存1天,path爲根目錄cookie
//設定cookie爲安全的(secure=true),只能在HTTPS或與其餘安全協議 //鏈接在一塊兒的時候才被傳輸 setCookie("phone","444",24,"/",".",false); alert(document.cookie); alert(getCookie("age")); //刪除名稱爲"age"的cookie removeCookie("age") alert(document.cookie); //刪除名稱爲"address"的cookie,由於設置時設定的path,因此刪除 //時也須要傳入對應path removeCookie("address","/") alert(document.cookie); } function setCookie(name,value,hours,path,domain,secure){ var cdata = name + "=" + value; if(hours){ var d = new Date(); d.setHours(d.getHours() + hours); cdata += "; expires=" + d.toGMTString(); } cdata +=path ? ("; path=" + path) : "" ; cdata +=domain ? ("; domain=" + domain) : "" ; cdata +=secure ? ("; secure=" + secure) : "" ; document.cookie = cdata; } function getCookie(name){ var reg = eval("/(?:^|;\\s*)" + name + "=([^=]+)(?:;|$)/"); return reg.test(document.cookie) ? RegExp.$1 : ""; } function removeCookie(name,path,domain){ this.setCookie(name,"",-1,path,domain); } </script>