This article mainlyintroducesHtml5Relevant information about the detailed description of web local storage examples. Friends in need can refer to it
Web Storage is introduced by HTML5 A very important function that can store data locally on the client, similar to HTML4's cookie, 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 disappears when the browser is closed; while localStorage always saves the data locally on the client;
No matter it SessionStorage or localStorage, the API that can be used are the same, the commonly used ones are as follows (take localStorage as an example):
Save data: localStorage.setItem (key,value);Read data: localStorage.getItem(key);DeleteSingle data: localStorage.removeItem(key);Delete all data: localStorage.clear ();Get the key of a index: localStorage.key(index);
As above, both key and value must be string, 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, and the contacts have names , mobile phone number 2 fields, use the mobile phone number as the key to store in localStorage; find the owner according to the mobile phone number; list all currently saved contact information;
First write a simple html code
<!DOCTYPEHTML> <html> <head> <metacharsetmetacharset="utf-8"/> <title>HTML5本地存储之WebStorage篇</title> </head> <body> <pstylepstyle="border:2pxdashed#ccc;width:320px;text-align:center;"> <labelforlabelfor="user_name">姓名:</label> <inputtypeinputtype="text"id="user_name"name="user_name"class="text"/> <br/> <labelforlabelfor="mobilephone">手机:</label> <inputtypeinputtype="text"id="mobilephone"name="mobilephone"/> <br/> <inputtypeinputtype="button"onclick="save()"value="新增记录"/> <hr/> <labelforlabelfor="search_phone">输入手机号:</label> <inputtypeinputtype="text"id="search_phone"name="search_phone"/> <inputtypeinputtype="button"onclick="find()"value="查找机主"/> <pidpid="find_result"><br/></p> </p> <br/> <pidpid="list"> </p> </body> </html>
After writing the page, the display effect will be almost as shown below:
To save contacts, you only need to implement it simply The following JS method is enough:
functionsave(){ varmobilephone=document.getElementById("mobilephone").value; varuser_name=document.getElementById("user_name").value; localStorage.setItem(mobilephone,user_name); } //用于保存数据
To find the owner, implement the following JS method:
//查找数据 functionfind(){ varsearch_phone=document.getElementById("search_phone").value; varname=localStorage.getItem(search_phone); varfind_result=document.getElementById("find_result"); find_result.innerHTML=search_phone+"的机主是:"+name; }
To display all saved contact information, you need to use the localStorage.key(index) method, as follows:
//将所有存储在localStorage中的对象提取出来,并展现到界面上 functionloadAll(){ varlist=document.getElementById("list"); if(localStorage.length>0){ varresult="<tableborder='1'>"; result+="<tr><td>姓名</td><td>手机号码</td></tr>"; for(vari=0;i<localStorage.length;i++){ varmobilephone=localStorage.key(i); varname=localStorage.getItem(mobilephone); result+="<tr><td>"+name+"</td><td>"+mobilephone+"</td></tr>"; } result+="</table>"; list.innerHTML=result; }else{ list.innerHTML="目前数据为空,赶紧开始加入联系人吧"; } }
The effect is as follows :
Question: The above demo only has two fields, name and mobile phone number. If you want to store richer contact information, such as company name, family Address, etc., how to implement it? Doesn't Web Storage only handle strings? At this time, you can use the stringify() method of JSON to convert the complex object into a string and store it in Web Storage; when reading from Web Storage, you can use The parse() method of JSON is then converted into a JSON object;
The following is a simple demonstration of adding the contact save JS code of the company attribute :
//保存数据 functionsave(){ varcontact=newObject; contact.user_name=document.getElementById("user_name").value; contact.mobilephone=document.getElementById("mobilephone").value; contact.company=document.getElementById("company").value; varstr=JSON.stringify(contact); localStorage.setItem(contact.mobilephone,str); loadAll(); } //将所有存储在localStorage中的对象提取出来,并展现到界面上 functionloadAll(){ varlist=document.getElementById("list"); if(localStorage.length>0){ varresult="<tableborder='1'>"; result+="<tr><td>姓名</td><td>手机</td><td>公司</td></tr>"; for(vari=0;i<localStorage.length;i++){ varmobilephone=localStorage.key(i); varstr=localStorage.getItem(mobilephone); varcontact=JSON.parse(str); result+="<tr><td>"+contact.user_name+"</td><td>"+contact.mobilephone+"</td><td>"+contact.company+"</td></tr>"; } result+="</table>"; list.innerHTML=result; }else{ list.innerHTML="目前数据为空,赶紧开始加入联系人吧"; } }
The effect is as follows:
The above is a detailed explanation of the Html5 web local storage example introduced by the editor. I hope it will be helpful to you. If you have any questions, please give us I leave a message
The above is the detailed content of Html5web local storage instance details. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using viewport meta tags to control page scaling on mobile devices, focusing on settings like width and initial-scale for optimal responsiveness and performance.Character count: 159

This article explains how to create and validate HTML5 forms. It details the <form> element, input types (text, email, number, etc.), and attributes (required, pattern, min, max). The advantages of HTML5 forms over older methods, incl

This article explains how to embed audio in HTML5 using the <audio> element, including best practices for format selection (MP3, Ogg Vorbis), file optimization, and JavaScript control for playback. It emphasizes using multiple audio f

This article details creating interactive HTML5 games using JavaScript. It covers game design, HTML structure, CSS styling, JavaScript logic (including event handling and animation), and audio integration. Essential JavaScript libraries (Phaser, Pi

The article discusses using the HTML5 Page Visibility API to detect page visibility, improve user experience, and optimize resource usage. Key aspects include pausing media, reducing CPU load, and managing analytics based on visibility changes.

The article discusses managing user location privacy and permissions using the Geolocation API, emphasizing best practices for requesting permissions, ensuring data security, and complying with privacy laws.

The article explains how to use the HTML5 Drag and Drop API to create interactive user interfaces, detailing steps to make elements draggable, handle key events, and enhance user experience with custom feedback. It also discusses common pitfalls to a

This article explains the HTML5 WebSockets API for real-time, bidirectional client-server communication. It details client-side (JavaScript) and server-side (Python/Flask) implementations, addressing challenges like scalability, state management, an


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),