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>
添加回答
举报