Home >Web Front-end >H5 Tutorial >HTML5 local storage Web Storage application introduction_html5 tutorial skills

HTML5 local storage Web Storage application introduction_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:50:361448browse

Web Storage is a very important feature introduced by HTML5. It can store data locally on the client, similar to HTML4 cookies, but its functions are much more powerful than cookies. The cookie size is limited to 4KB. Web Storage officially recommends that each Website 5MB.
Web Storage is divided into two types :
sessionStorage
localStorage
It can be clearly seen from the literal meaning that sessionStorage saves the data in the session and the browser is closed. That’s gone; localStorage always saves data locally on the client;
Whether it is sessionStorage or localStorage, the APIs that can be used are the same, and the commonly used ones are as follows (taking localStorage as an example):
Save data: localStorage.setItem(key,value);
Read data: localStorage.getItem(key);
Delete single data: localStorage.removeItem(key);
Delete all data: localStorage.clear ();
Get the key of an index: localStorage.key(index);
As above, both key and value must be strings. In other words, the web Storage API can only operate on strings.
Next, we develop a simple address book applet through Web Storage to demonstrate the use of relevant APIs; we want to implement the following functions:
Enter contacts. Contacts have two fields: name and mobile phone number. , use the mobile phone number as the key to store it in localStorage;
Find the owner according to the mobile phone number;
List all currently saved contact information;
First, prepare a simple HTML page, As follows :

Copy code
The code is as follows:





Web Storage of HTML5 Local Storage</title> ; <br /></head> <br><body> <br><div style="border: 2px dashed #ccc;width:320px;text-align:center;"> <br>< label for="user_name">Name:</label> <br><input type="text" id="user_name" name="user_name" class="text"/> <br><br /> <br><label for="mobilephone">Mobile phone: </label> <br><input type="text" id="mobilephone" name="mobilephone"/> <br> <br/> <br><input type="button" onclick="save()" value="New record"/> <br><hr/> <br><label for ="search_phone">Enter mobile phone number:</label> <br><input type="text" id="search_phone" name="search_phone"/> <br><input type="button" onclick="find()" value="Find owner"/> <br><p id="find_result"><br/></p> <br></div> <br><br/> <br><div id="list"> <br></div> <br></body> <br></html> <br> </div> <br><strong>The interface is shown as follows</strong>: <br><img alt="" src="http://files.jb51.net/file_images/article/201301/2013010615435390.png" align="middle"> <br>To save contacts, you only need to simply implement the following JS method: <br><br><div class="msgheader"> <div class="right"><span style="CURSOR: pointer" onclick="copycode(getid('phpcode74'));"><u>Copy code</u></span></div>The code is as follows:</div> <div class="msgborder" id="phpcode74"> <br>//Save data<br>function save(){ <br>var mobilephone = document .getElementById("mobilephone").value; <br>var user_name = document.getElementById("user_name").value; <br>localStorage.setItem(mobilephone,user_name); <br>} <br> </div> <br><strong>To find the owner, implement the following JS method</strong>: <br><br><div class="msgheader"> <div class="right"><span style="CURSOR: pointer" onclick="copycode(getid('phpcode75'));"><u>Copy code</u></span></div>Code As follows: </div> <div class="msgborder" id="phpcode75"> <br>//Find data<br>function find(){ <br>var search_phone = document.getElementById("search_phone").value; <br>var name = localStorage.getItem( search_phone); <br>var find_result = document.getElementById("find_result"); <br>find_result.innerHTML = search_phone "The owner is: " name; <br>} <br> </div> <br><img alt="" src="http://files.jb51.net/file_images/article/201301/2013010615435391.png" align="middle"><br>To display all saved contact information, you need to use the localStorage.key(index) method, as follows: <br><br><div class="msgheader"> <div class="right"><span style="CURSOR: pointer" onclick="copycode(getid('phpcode76'));"><u>Copy code</u> </span></div>The code is as follows:</div> <div class="msgborder" id="phpcode76"> <br>//Extract all objects stored in localStorage and display them on the interface <br>function loadAll(){ <br>var list = document.getElementById("list"); <br> if(localStorage.length>0){ <br>var result = "<table border='1'>"; <br>result = "<tr><td>Name</td>< td>Mobile phone number</td></tr>"; <br>for(var i=0;i<localStorage.length;i ){ <br>var mobilephone = localStorage.key(i); <br>var name = localStorage.getItem(mobilephone); <br>result = "<tr><td>" name "</td><td>" mobilephone "</td></tr> "; <br>} <br>result = "</table>"; <br>list.innerHTML = result; <br>}else{ <br>list.innerHTML = "The data is currently empty, start adding now Contact Bar"; <br>} <br>} <br> </div> <br>The effect is as follows: <br><img alt="" src="http://files.jb51.net/file_images/article/201301/2013010615435392.png" align="middle"> <br>Problem: The above demo only has 2 fields, name and mobile phone number , if you want to store richer contact information, such as company name, home address, etc., how to achieve it? Doesn't Web Storage only handle strings? At this time, you can use JSON's stringify() method to convert complex objects into strings and store them in Web Storage; when reading from Web Storage, you can use JSON's parse() method to convert them into JSON objects; <br><strong>The following is a simple demonstration of adding the JS code for saving contacts with company attributes</strong>: <br><br><div class="msgheader"> <div class="right"><span style="CURSOR: pointer" onclick="copycode(getid('phpcode77'));"><u>Copy code</u></span></div>The code is as follows: </div> <div class="msgborder" id="phpcode77"> <br>//Save data<br>function save(){ <br>var contact = new Object; <br>contact.user_name = document.getElementById("user_name"). value; <br>contact.mobilephone = document.getElementById("mobilephone").value; <br>contact.company = document.getElementById("company").value; <br>var str = JSON.stringify(contact) ; <br>localStorage.setItem(contact.mobilephone,str); <br>loadAll(); <br>} <br>//Extract all objects stored in localStorage and display them on the interface<br> function loadAll(){ <br>var list = document.getElementById("list"); <br>if(localStorage.length>0){ <br>var result = "<table border='1'>" ; <br>result = "<tr><td>Name</td><td>Mobile phone</td><td>Company</td></tr>"; <br>for(var i=0;i<localStorage.length;i ){ <br>var mobilephone = localStorage.key(i); <br>var str = localStorage.getItem(mobilephone); <br>var contact = JSON .parse(str); <br>result = "<tr><td>" contact.user_name "</td><td>" contact.mobilephone "</td><td>" contact .company "</td></tr>"; <br>} <br>result = "</table>"; <br>list.innerHTML = result; <br>}else{ <br> list.innerHTML = "The data is currently empty, start adding contacts quickly"; <br>} <br>} <br> </div> <br>The effect is as follows: <br><img alt="" src="http://files.jb51.net/file_images/article/201301/2013010615435393.png" align="middle"></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="HTML5 Reshapes the Web World How Will It Change the Internet_html5 Tutorial Tips" href="https://m.php.cn/faq/6528.html">HTML5 Reshapes the Web World How Will It Change the Internet_html5 Tutorial Tips</a></span><span>Next article:<a class="dBlack" title="HTML5 Reshapes the Web World How Will It Change the Internet_html5 Tutorial Tips" href="https://m.php.cn/faq/6531.html">HTML5 Reshapes the Web World How Will It Change the Internet_html5 Tutorial Tips</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/348281.html" title="AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds" class="aBlack">AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348372.html" title="HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)" class="aBlack">HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348373.html" title="Detailed explanation of image drawing examples in HTML5 canvas 9" class="aBlack">Detailed explanation of image drawing examples in HTML5 canvas 9</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348374.html" title="Regular expressions and new HTML5 elements" class="aBlack">Regular expressions and new HTML5 elements</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/348469.html" title="How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server" class="aBlack">How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body><!-- Matomo --><script> var _paq = window._paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://tongji.php.cn/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '9']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script><!-- End Matomo Code --></html>