在HTML5中,加入了一个localStorage对象,这个对象主要是用来进行本地存储使用的。localStorage拓展了cookie的4K限制,localStorage相当于一个5M的前端页面数据库,对于某些数据,比如图片、搜索记录可以直接存在浏览器端,从而减小带宽。
localStorage用于长久保存整个网站的数据,保存的数据没有过期时间,除非手动删除。而cookie则是用过期时间,到时会自动删除。
(1)保存数据
localStorage.setItem(key,value);
(2)读取数据
localStorage.getItem(key);
(3)移除数据
localStorage.removeItem(key);
(4)清空localStorage所有数据
localStorage.clear()
另外,由于localStorage存储的都是字符串,如果value设置为一个对象,则会调用该对象的toString()方法,然后存储。
localStorage.setItem("person",{"name": "xiaoming",toString: function(){ return this.name;}})
结果:
一般我们会将JSON存入localStorage中,这个时候我们就可以使用JSON.stringfy()方法来将JSON转换为JSON字符串。在读取的时候,使用JSON.parse()转换为JSON对象。
这里使用localStorage来保存搜索记录,顺便复习下art-template,利用模板引擎来渲染页面
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>首页</title> <style> *{ margin: 0; padding: 0; } body{ margin-left: 300px; } ul{ list-style: none; } ul li,div{ width: 250px; padding: 10px 0; margin-left: 10px; border-bottom: 1px dashed #ccc; height: 20px; } a{ float: right; } input{ padding: 5px; margin: 10px; } </style> </head> <body> <input type="search" placeholder="输入搜索关键字"/> <input type="button" value="搜索"/> <div id="del"><a href="javascript:;">清空搜索记录</a></div> <ul id="uu"> <li>没有搜索记录</li> </ul> <script src="jquery.min.js"></script> <script src="template-web.js"></script> <script id="tpl-search" type="text/html"> {{ each historys }} <li data-index="{{ $index }}"><span>{{ $value }}</span><a href="javascript:;">删除</a></li> {{/each}} </script> <script> $(function () { //当搜索时向localStorage存储 var historyList = window.localStorage.getItem("historys") || '[]'; //存储在localStorage中的都是string类型 var historys = JSON.parse(historyList); //转为数组对象 $("[type=button]").on("click", function () { var keywords = $("[type=search]").val(); if(!keywords){ alert("请填值"); $("[type=search]").focus(); return false; } historys.push(keywords); window.localStorage.setItem("historys",JSON.stringify(historys)); render(); }); //根据localStorage向页面渲染, var render = function () { var html = template("tpl-search", {"historys": historys}); //利用模板art-template渲染页面 html = html || "<li>没有搜索记录</li>"; $("#uu").html(html); }; render(); //刚进页面就渲染页面 //单条删除 $("#uu").on("click","a", function () { var index = $(this).parent().data("index"); historys.splice(index,1); window.localStorage.setItem("historys", JSON.stringify(historys)); render(); }); //清空历史记录 $("#del").on("click","a",function () { historys = []; window.localStorage.setItem("historys", JSON.stringify(historys)); render(); }) // localStorage.removeItem("name") // localStorage.clear() }); </script> </body> </html>
注:关于art-templete的使用注意:
templete(filename,content)
这个函数是用来加载模板的,通常返回的是经过渲染的html代码。
其中第一个参数filename是在<script></script>标签中定义的id值,第二个参数是一个对象,形式为{Object,string},这个数据会传到定义的模板中来渲染。