js操作cookie儲存瀏覽記錄的方法_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了js操作cookie儲存瀏覽記錄的方法。分享給大家供大家參考,具體如下:

說明:最近做了一個功能,記錄使用者瀏覽過的產品頁面。我的思路是,客戶每次進入產品頁面,就自己調用JS把產品資訊以json的形式儲存到cookie裡面。

瀏覽記錄的顯示是從cookie裡讀出來,然後解析成json,產生html元素。因為使用者可能會同時開啟好幾個頁面,這幾個頁面上可能都有瀏覽記錄,為了使即使顯示瀏覽記錄,每秒中重新整理一次。

要用到2個js檔案,history.js,關鍵的聊天記錄儲存和讀取代碼。json.js,對json進行處理。

history.js

var addHistory=function(num,id){  stringCookie=getCookie('history');  var stringHistory=""!=stringCookie?stringCookie:"{history:[]}";  var json=new JSON(stringHistory);  var e="{num:"+num+",id:"+id+"}";  json['history'].push(e);//添加一個新的記錄  setCookie('history',json.toString(),30);}//顯示記錄var DisplayHistory=function(){  var p_ele=document.getElementById('history');   while (p_ele.firstChild) {   p_ele.removeChild(p_ele.firstChild);   }  var historyJSON=getCookie('history');  var json=new JSON(historyJSON);  var displayNum=6;  for(i=json['history'].length-1;i>0;i--){    addLi(json['history'][i]['num'],json['history'][i]['id'],"history");     displayNum--;    if(displayNum==0){break;}  }}//添加一個li元素var addLi=function(num,id,pid){  var a=document.createElement('a');  var href='product.action?pid='+id;  a.setAttribute('href',href);  var t=document.createTextNode(num);  a.appendChild(t);  var li=document.createElement('li');  li.appendChild(a);  document.getElementById(pid).appendChild(li);}//添加cookievar setCookie=function(c_name,value,expiredays){  var exdate=new Date()  exdate.setDate(exdate.getDate()+expiredays)  cookieVal=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());//  alert(cookieVal);  document.cookie=cookieVal;}//擷取cookiefunction 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//    document.write(document.cookie.substring(c_start,c_end)+"<br>");    return unescape(document.cookie.substring(c_start,c_end))    }   }  return ""}

json.js

var JSON = function(sJSON){  this.objType = (typeof sJSON);  this.self = [];  (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);}JSON.prototype = {  toString:function(){    return this.getString();  },  valueOf:function(){    return this.getString();  },  getString:function(){    var sA = [];    (function(o){      var oo = null;      sA.push('{');      for(var i in o){        if(o.hasOwnProperty(i) && i!='prototype'){          oo = o[i];          if(oo instanceof Array){            sA.push(i+':[');            for(var b in oo){              if(oo.hasOwnProperty(b) && b!='prototype'){                sA.push(oo[b]+',');                if(typeof oo[b]=='object') arguments.callee(oo[b]);              }            }            sA.push('],');            continue;          }else{            sA.push(i+':'+oo+',');          }          if(typeof oo=='object') arguments.callee(oo);        }      }      sA.push('},');    })(this.self);    return sA.slice(0).join('').replace(/objectobject,/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);  },  push:function(sName,sValue){    this.self[sName] = sValue;    this[sName] = sValue;  }}

希望本文所述對大家JavaScript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.