标签:oat key 今天 gettime first enter idt ext type
好久没写博客了。今天就写一个小demo。
使用cookie记录每次点击的历史记录,并且以json的格式存入cookie,如果相同的浏览记录,则不记录
demo中只设置了记录最新的3条数据。。
if (len > 2) { json1.splice(0, 1); }
更多的可修改下面代码中的 2。
具体代码如下:
html部分:
<div class="clx-3"> <ul id="searchCityListB"> <li><a class="col1" data-areaId="1" >测试1</a></li> <li><a class="col1" data-areaId="2" ><span class="">测试2</span></a></li> <li><a class="col1" data-areaId="3" ><span class="">测试3</span></a></li> <li><a class="col1" data-areaId="4" ><span class="">测试4</span></a></li> <li><a class="col1" data-areaId="5" ><span class="">测试5</span></a></li> <li><a class="col1" data-areaId="6" ><span class="">测试6</span></a></li> </ul> </div>
css部分:
*{margin:0; padding: 0;} .clx-3{ width: 100%;} .clx-3 li{ float: left; list-style: none; width: 33.333%; line-height: 50px; text-align: center; border-bottom: #ddd 1px solid; border-right: #ddd 1px solid; box-sizing: border-box} .clx-3 li:nth-child(3n+0){ border-right: none}
js部分:
$(document).on(‘click‘, ‘#searchCityListB li‘, function (event) { var areaIdS = $(this).children().attr("data-areaid"); var cityNameS = $(this).children().text(); setHistoryK(cityNameS, areaIdS); }); //设置cookies function setHistoryK(cityNameS, areaIdS) { var len = 0; var canAdd = true; var historyData, json1; var firstStr = " [" + " {\"cityName\":\"" + cityNameS + "\"," + " \"areaId\":" + areaIdS + "}" + " ]"; var jsonFirstStr = JSON.stringify(firstStr); if (!getCookie("cityHistory")) { //第一次的时候需要初始化 setCookie("cityHistory", jsonFirstStr); } else { //已经存在 historyData = getCookie("cityHistory"); json1 = eval("(" + historyData + ")"); if (typeof(json1) == "string") { json1 = JSON.parse(json1); } len = json1.length; $(json1).each(function () { if (this.cityName == cityNameS) { canAdd = false; return false; } }); if (canAdd == true) { if (len > 2) { json1.splice(0, 1); } var newJsonStr = {"cityName": cityNameS, "areaId": areaIdS},jsonSetStr; json1.push(newJsonStr); //添加一个新的记录 jsonSetStr = JSON.stringify(json1); setCookie("cityHistory", jsonSetStr); console.log(jsonSetStr); } } }
引用一个cookie.js
具体代码如下:
//写cookies function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } //获取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return unescape(arr[2]); else return null; } //检查cookies function checkCookie(c_name){ if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start>0) var arr = new Array(); arr = document.cookie.split(";"); return arr.length } } //删除cookies function delCookie(name) { var keys=document.cookie.match(/[^ =;]+(?=\=)/g); if (keys) { for (var i = keys.length; i--;) document.cookie=keys[i]+‘=0;expires=‘ + new Date( 0).toUTCString() } }
标签:oat key 今天 gettime first enter idt ext type
原文地址:http://www.cnblogs.com/webQdesign/p/6398866.html