JS通过Cookie判断页面是否为首次打开
废话不多说了,直接给大家贴代码了,本文写的不好还请各位大侠见谅。
JScriptcode:
functionCookie(key,value) { this.key=key; if(value!=null) { this.value=escape(value); } this.expiresTime=null; this.domain=null; this.path="/"; this.secure=null; } Cookie.prototype.setValue=function(value){this.value=escape(value);} Cookie.prototype.getValue=function(){return(this.value);} Cookie.prototype.setExpiresTime=function(time){this.expiresTime=time;} Cookie.prototype.getExpiresTime=function(){returnthis.expiresTime;} Cookie.prototype.setDomain=function(domain){this.domain=domain;} Cookie.prototype.getDomain=function(){returnthis.domain;} Cookie.prototype.setPath=function(path){this.path=path;} Cookie.prototype.getPath=function(){returnthis.path;} Cookie.prototype.Write=function(v) { if(v!=null) { this.setValue(v); } varck=this.key+"="+this.value; if(this.expiresTime!=null) { try { ck+=";expires="+this.expiresTime.toUTCString();; } catch(err) { alert("expiresTime参数错误"); } } if(this.domain!=null) { ck+=";domain="+this.domain; } if(this.path!=null) { ck+=";path="+this.path; } if(this.secure!=null) { ck+=";secure"; } document.cookie=ck; } Cookie.prototype.Read=function() { try { varcks=document.cookie.split(";"); vari=0; for(i=0;i<cks.length;i++) { varck=cks[i]; varfields=ck.split("="); if(fields[0]==this.key) { this.value=fields[1]; return(this.value); } } returnnull; } catch(err) { alert("cookie读取错误"); returnnull; } }
HTMLcode:
<scripttype="text/javascript"src="Cookie.js"></script> <scripttype="text/javascript"language="javascript"> window.onload=function(){ varck=newCookie("HasLoaded");//每个页面的newCookie名HasLoaded不能相同 if(ck.Read()==null){//未加载过,Cookie内容为空 alert("首次打开页面"); //设置保存时间 vardd=newDate(); dd=newDate(dd.getYear()+1900,dd.getMonth(),dd.getDate()); dd.setDate(dd.getDate()+365); ck.setExpiresTime(dd); ck.Write("true");//设置Cookie。只要IE不关闭,Cookie就一直存在 } else{//Cookie存在,表示页面是被刷新的 alert("页面刷新"); } } </script>
以上所述是小编给大家分享JS通过Cookie判断页面是否为首次打开的相关内容,希望对大家有所帮助。