javascript 操作 cookie 的方法
问题:使得在访问页面的时候能够沿用上次的设置,或者在不同的页面间共享数据。比如
用户在访问网站的时候设置了页面字体的大小,那么会希望下次访问的时候仍然能使用同
样的设置进行浏览,而不用重复设置。
解决方案:在用户浏览页面并进行设置时,将这些设置保存在 cookie 中,下次访问的时
候读取
cookie 中的设置。参考下面的脚本:
// utility function to retrieve an expiration data in proper format;
function getExpDate(days, hours, minutes)
{
var expDate = new Date();
if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) ==
"number")
{
expDate.setDate(expDate.getDate() + parseInt(days));
expDate.setHours(expDate.getHours() + parseInt(hours));
expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
return expDate.toGMTString();
}
}
//utility function called by getCookie()
function getCookieVal(offset)
{
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1)
{
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
// primary function to retrieve cookie by name
function getCookie(name)
{
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while(i < clen)
{
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
{
return getCookieVal(j);
}