h5中localStorage的使用方法
h5中的localStorage现在广泛流行于移动端的应用中,可以保存相关的信息在本地存储,并且存储的时间非常长,一般不是人为清除会一直保存。
这里记录之前使用的一段代码:
$(document).delegate(".delete>div","click",function(){ $("#keyboard2").val($(this).text()); }); var hisTime; var hisItem; var firstKey; function init (){ hisTime = []; hisItem = []; var i=0 for(;i<localStorage.length;i++){ if(!isNaN(localStorage.key(i))){ hisItem.push(localStorage.getItem(localStorage.key(i))); hisTime.push(localStorage.key(i)); } } i=0; $(".delete").html(""); for(;i<hisItem.length;i++){ $(".delete").prepend('<div class="word-break" id=""style=" z-index: 1000;">'+hisItem[i]+'</div>') } } init(); $(".search-button").click(function(){ var value = $("#keyboard2").val(); var time = (new Date()).getTime(); if(!value){ alert("你未输入搜索内容"); return false; } if($.inArray(value,hisItem)>=0){ for(var j = 0;j<localStorage.length;j++){ if(value==localStorage.getItem(localStorage.key(j))){ localStorage.removeItem(localStorage.key(j)); } } localStorage.setItem(time,value); }else{ if(hisItem.length>4){ firstKey = hisTime[0] localStorage.removeItem(firstKey); localStorage.setItem(time,value); }else{ localStorage.setItem(time,value) } } init(); }); //清除记录功能 $("#his-dele").click(function(){ var f = 0; for(;f<hisTime.length;f++){ localStorage.removeItem(hisTime[f]); } init(); }); //苹果手机不兼容出现input无法取值以下是解决方法 $(function(){ $('.word-break').click(function(){ var div = $(this).text(); $('#keyboard2').val(div); }) //取到值以后button存储无法取值,这里强迫浏览器强行刷新可解决 $('.search-button').click(function(){ window.location.reload(); }) })