通過cookie記錄,設置頁面訪問的跳轉頁
目的:
1.訪問fm.html時,假如沒訪問過,跳轉到fm1.html,訪問1次后,跳轉到fm2.html,訪問2次后,跳轉到fm3.html,再次訪問跳fm1.html,依次循環
原理:
通過cookie保存訪問記錄:沒訪問過時,保存cookie1,訪問1次后,保存cookie2,訪問2次后,保存cookie3,再次訪問fm.html,清除cookie
關鍵代碼:
1.保存cookie
- function setCookie(name,value) {
- var Days = 365;
- var exp = new Date();
- exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
- document.cookie = name + ("=" + (value) + ";expires=" + exp.toGMTString() + ";path=/;");}
2.讀取cookie
- function getCookie(name){
- var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
- if (arr != null) {
- return (arr[2]);
- }
- return null;
- }
3.刪除cookie
- function delCookie(name){//為了刪除指定名稱的cookie,可以將其過期時間設定為一個過去的時間
- var date = new Date();
- date.setTime(date.getTime() - 10000);
- document.cookie = name + "=a; expires=" + date.toGMTString();
- }
- 另一種方法刪除cookie
- setcookie("cookiename","")設置某個cookiename值為空
4.跳轉代碼
- var url=window.location.href;
- var history=getCookie("his");
- if(history==""||history==null){
- setCookie("his","http://127.0.0.1/fm1.html");
- window.location.href="fm1.html"
- }else{
- var index=history.lastIndexOf("/");
- var cururl=history.substring(index+3,index+4);
- var cururll=parseInt(cururl);
- switch(cururll){
- case 1:
- setCookie("his","http://127.0.0.1/fm2.html");
- window.location.href="fm2.html";
- break;
- case 2:
- setCookie("his","http://127.0.0.1/fm3.html");
- window.location.href="fm3.html";
- break;
- default:
- delCookie("his");
- window.location.href="fm.html"
- }
- }