匿名用户
1级
2009-11-28 回答
因为HTML不能记录当前的目录(index),再加上每次刷新都要用到不同的值,所以我的方法是用cookie来解决这个。下面要用到2个方法,一个是getcookie(c_name),调用名字为c_name的cookie,还有一个是setCookie(c_name,value,expiredays),设置一个cookie,定义它的名字为c_name,值为value,有效期为expiredays。
然后在body中的代码。当打开这个网页时,查询是否有tipsIndex的值,如果用户第一次访问这个页面,则把tipsIndex的值设为0,如果之前访问过则调用之前的值,在显示完相应的tips以后更新tipsIndex的值(mod tips的总数,防止超过tips的数量)然后写入cookie里,以方便下次刷新的时候使用。
以下是代码,已经过测试,希望对你有所帮助
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function 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());
}
tips = new Array();
tips[0]='多难兴邦!';
tips[1]='逝者安息,生者坚强。';
tips[2]='2008年5月12日14点28分';
tips[3]='相信奇迹总会发生的。';
tips[4]='逆境中成长,北京人民的爱国激情在燃烧。';
tips[5]='抗震救灾,众志成城。';
tips[6]='深切哀悼汶川大地震遇难同胞。';
tips[7]='2008年5月19日至21日,全国哀悼日。';
tips[8]='May their souls rest in Eternal Peace...';
tips[9]='My thoughts are with you all.';
tipsIndex=getCookie('tipsIndex');//read cookie
if (tipsIndex==null || tipsIndex=="")
{
setCookie('tipsIndex',0,365);
tipsIndex=getCookie('tipsIndex');
}
document.write(tips[tipsIndex]);
tipsIndex++;
setCookie('tipsIndex',tipsIndex%tips.length,365);