4 回答

TA貢獻1963條經驗 獲得超6個贊
js保存COOKIE,直接給document加上cookie就可以了,但是一般如果單個的加會很麻煩所以一般會直接寫好一個函數,可以直接操作cookie,這樣就很方便了
setCookie這個是寫入cookie,第一個是名稱,第二個是cookie值,第三個是過期時間
getCookie這個是查找cookie;
removeCookie這是你需要刪除的cookie;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | function setCookie(name, value, iDay) { var oDate=new Date();
oDate.setDate(oDate.getDate()+iDay);
document.cookie=name+'='+encodeURIComponent(value)+';expires='+oDate; }
function getCookie(name) { var arr=document.cookie.split('; '); var i=0; for(i=0;i<arr.length;i++) { //arr2->['username', 'abc'] var arr2=arr[i].split('=');
if(arr2[0]==name) { var getC = decodeURIComponent(arr2[1]); return getC; } }
return ''; }
function removeCookie(name) { setCookie(name, '1', -1); } |

TA貢獻1887條經驗 獲得超5個贊
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="白菜編輯部">
<title>白菜編輯部</title>
<style type="text/css">
</style>
<script type="text/javascript">
function readCookie (name)
{
var cookieValue = "";
var search = name + "=";
if (document.cookie.length > 0)
{
offset = document.cookie.indexOf (search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexOf (";", offset);
if (end == -1)
end = document.cookie.length;
cookieValue = unescape (document.cookie.substring (offset, end))
}
}
return cookieValue;
}
function writeCookie (name, value, hours)
{
var expire = "";
if (hours != null)
{
expire = new Date ((new Date ()).getTime () + hours * 3600000);
expire = "; expires=" + expire.toGMTString ();
}
document.cookie = name + "=" + escape (value) + expire;
}
writeCookie ("myCookie", "my name", 24);
alert (readCookie ("myCookie"));
</script>
</head>
<body>
</body>
</html>
添加回答
舉報