代码乱掉了。。。移步

得益于H5的API,前端可以很方便的存储数据,除了cookie,新增的sessionStorage、localStorage可以在用户本地存储数据,这可以让前端实现一些,以前只能有数据库存储的功能。

搜索记录可以用前端实现,由于这些数据没有特别安全的要求,用户搜索过的关键词保存在用户本地是完全可以的。这样做也可以减少服务器的压力。

搜索记录应该采用localStorage永久的存储,当用户下次访问的时候,这个数据还在。

下面的例子是手机端网页,布局比较粗糙,除了替换搜索的按钮图片。其他的功能都正常。

主要思路:在向localStorage存储的时候,以点击搜索的时间戳为key,以搜索的词语为value.最多存储6条数据。当超过6条,会删除最早的记录。

localStorage的存储是有顺序的,最先存的会在最底下。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>1元许愿</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="no">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
<style>
.text-center{text-align:center;}
.box{display:-webkit-box;display:box;}
#idNumber1{width:80%;overflow:hidden;text-align:left;display:block;max-height:100%;border:1px solid #0C0;}
.his-record:after {clear:both;content:'.';display:block;width: 0;height: 0;visibility:hidden;} {}
.his-record>div{float:left;width:31%;margin:0.5rem 1%;padding:5px 6%;border-radius:3px;border:1px solid #999;color:#999;}

</style>
</head>
<body>
	<section>
    	<div class="box" style="border-radius:5px;">
        	<form >
        	<input class="" >
            </form>
     		<div style="width:20%;background:url(../assets/images/yy/search.jpg) no-repeat right;background-size:contain;" ></div>
        </div>
    </section>
    
    <section class="his-record text-center">
    </section>
     <!--清空历史记录-->
    <section style="position:fixed;bottom:70px;width:100%;">
    	<div class="font-brown text-center" style="border:2px solid #834f1b;padding:3px 15px;margin:0 auto;width:40%;" >清空搜索记录</div>
    </section>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
	$(document).delegate(".his-record>div","click",function(){
		$("#idNumber1").val($(this).text());	
	});

	/*搜索记录相关*/
	//从localStorage获取搜索时间的数组
	var hisTime;
	//从localStorage获取搜索内容的数组
	var hisItem;
	//从localStorage获取最早的1个搜索时间
	var firstKey;
	function init (){
	//每次执行都把2个数组置空
	hisTime = [];
	hisItem = [];
	//模拟localStorage本来有的记录
	localStorage.setItem("a",12333);
	//本函数内的两个for循环用到的变量
	var i=0
	
	for(;i<localStorage.length;i++){
		
		//alert(typeof(localStorage.key(i)));
		if(!isNaN(localStorage.key(i))){
		  //hisItem.push(localStorage.getItem(localStorage.key(i)));
		  hisTime.push(localStorage.key(i));
		}
	  }
hisTime.sort();
   for(var y=hisTime.length;y>-1;y--){  
         hisItem.push(localStorage.getItem(hisTime[y]));
} 

  代码分析参见下篇博客

  

  预览如下:

前端实现搜索记录功能

相关文章: