保存页面的浏览记录
我的设计思想是将用户的浏览记录保存到cookie里面,然后根据情况处理。cookie里面的数据格式是json格式,方便根据自己的需要添加或者修改属性。
引用了3个js文件,下载地址如下。
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>浏览记录</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 6 <script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script> 7 <script type="text/javascript" src="../js/jquery.cookie.js"></script> 8 <script type="text/javascript" src="../js/json2.js"></script> 9 <script type="text/javascript"> 10 String.prototype.format = function (args) { 11 if (arguments.length > 0) { 12 var result = this; 13 if (arguments.length == 1 && typeof (args) == "object") { 14 for (var key in args) { 15 var reg = new RegExp("({" + key + "})", "g"); 16 result = result.replace(reg, args[key]); 17 } 18 } 19 else { 20 for (var i = 0; i < arguments.length; i++) { 21 if (arguments[i] == undefined) { 22 return ""; 23 } 24 else { 25 var reg = new RegExp("({[" + i + "]})", "g"); 26 result = result.replace(reg, arguments[i]); 27 } 28 } 29 } 30 return result; 31 } 32 else { 33 return this; 34 } 35 } 36 37 //添加一个新的浏览记录 38 function addHistory(productName, url) { 39 var historyArr = getHistory(); 40 historyArr.push({'productName':productName, 'url':url}); 41 $.cookie('overviewHistory', JSON.stringify(historyArr), { expires:7, path:'/' }); 42 } 43 //获取所有的浏览记录 44 function getHistory() { 45 var overviewHistory = $.cookie('overviewHistory'); 46 if (typeof overviewHistory === "undefined") { 47 return [] 48 } else { 49 return eval("(" + overviewHistory + ")"); 50 } 51 } 52 //将浏览记录显示到相应的元素里面 53 function updateHistoryEle() { 54 var historyArr = getHistory(); 55 historyArr.reverse() 56 //设置最大的显示数量 57 while (historyArr.length > 10) { 58 historyArr.pop() 59 } 60 for (i = 0; i < historyArr.length; i++) { 61 $('<div><a href="{1}">{0}</a></div>'.format(historyArr[i].productName, historyArr[i].url)).appendTo('#history'); 62 } 63 } 64 65 $(function () { 66 addHistory("亲的", "www.baidu.com") 67 updateHistoryEle() 68 }) 69 </script> 70 </head> 71 <body> 72 <div id="history"> 73 74 </div> 75 </body> 76 </html>