JavaScript_Html5_LocalStorage project demo, localstoragedemo
The localStorage utility in the project
In the project, the local storage of h5 is small and practical. It is intended to use cookies. However, if chrome debugging is disabled, localStorage is used.
This is a post-Bar search page. When a new user clicks the search box for the first time, the search page is displayed. When an old user clicks the search box, a search record is displayed, the implementation method is to create a local storage localStorage user-data for the user when you click the search button, when the page contains user-data, the val in the search box is appended to user-data and separated by "|". If user-data does not exist, user-data is created.
1 var storage=window.localStorage;2 if(storage.getItem("user-data")){3 var str=storage.getItem("user-data");4 storage.setItem("user-data",str+'|'+$('#keyword').val());5 }else{6 storage.setItem("user-data",$('#keyword').val());7 }
When a page is loaded, if the local localStorage contains user-data, the data is obtained and returned as a string. The split method is used to cut the string into an array based on the "|" condition, and create them cyclically. import them to the page editor, that is:
If ($ ('. search-con ')&&! FindKey ('keyword') {var html = ""; if (window. localStorage & localStorage. getItem ("user-data") {var data = localStorage. getItem ("user-data "). split ('|'); for (var I = data. length-1; I> = 0; I --) {html + = "<div class = 'user-his '>" + data [I] + "</div>"} $ ('. user-clear '). show ();} else {html = '<I class = "iconfont icon-wenbensousuo"> </I> <br> <span> no information found </span> '{}('.search-con'}.html (html );}
The findKey () method is used to determine whether the path contains the search keyword keyWords. The requirement is that the search result is displayed when the search keyword is contained, so you do not need to pay attention to it.
1 function findKey(name){2 var str=window.location.href;3 return str.indexOf(name)==-1?false:true;4 }
When you click CLEAR search records, clear user-data, that is:
1 localStorage.removeItem("user-data");
When you click search, the search box is spelled out, and the page is refreshed to obtain the background data, the ajaxrequest is sent, and the search.html is the relative path, that is, the current file name:
1 window.location.href='search.html?keyWords='+encodeURI($('#keyword').val());
To achieve this, you only need to have one backend page (we use asp.net as the backend) and paste the complete test code:
<! DOCTYPE html>
Directly copy to the portable file for testing. The portable state is better for mobile devices. If keywordsis included in the portable file, it is the test data. Deleting the data after .html is the search page. If you have any questions or errors, please contact us. Thank you ~~