Exploring the use of HTML5 local storage functions (1)
Through examples, we can deepen our understanding of HTML5 local storage and use it skillfully.
To implement a simple application, the user enters the user name and mobile phone number in the application. The attack can be saved to the local device, and basic operations such as search and display can be performed.
The following is only the key code for me. You can add the project structure, basic code, and CSS style by yourself.
The distribution is completed according to the function.
1. Storage Functions
Here we need to complete the process. When you enter your name and mobile phone number, your information is stored in Web Storage. The code in html is as follows:
<Form> <labelfor = "username"> Name: <inputtype = "text" id = "" username "" name = "" username ""> <labelfor = "mobilephone"> mobile phone number: <input id = "" mobilephone "" name = "" mobilephone "" type = "" text ""/> <input onclick = "" save () "vale =" add record "" type = "" button "/> </labelfor =" mobilephone "> </inputtype =" text "> </labelfor =" username"> </form>
The above code is a form. after entering the name and mobile phone number, you can click Add record to save the name-mobile phone number key-Value Pair locally. The specific code of the save Function in js is as follows:
function save(){ var mobilePhone= document.getElementById(“mobilephone”).value; var userName= dpcument.getElementById(“username”).value;localStorage.setItem(mobilePhone,userName);}
The logic of the Save function is very simple, that is, to extract the value entered by the user, and then store the information to Web Storage in the form of key-value pairs using the setItem function of localStorage.
2. Search
The search function needs to be implemented. When a user enters a phone number, the corresponding search information in the database is displayed. The HTML code is as follows:
<Label for = "" search ""> enter the mobile phone number: </label> <input type = "" text "" id = "" search "" data-cke-saved-name = "" search "" name = "" search "" data-cke-editable = "1" contenteditable = "false"> <input type = "" button "data-cke-editable =" 1 "contenteditable =" false "data- cke-pa-onclick = "" find () "value =" Search "">
The result area is used to place the query results. The following code describes the find function in js:
function find(){ var search =document.getElementById(“search”).value; var name = localStorge.gteItem(search); var result =document.getElementById(“result”); result.innerHTML= search + “:” + name;}
First, obtain the mobile phone number entered by the user, and then use getItem to zoom in to obtain the user name with the mobile phone number as this from the database, and then display it in the result area.
The above two are the most basic functions. We will continue to explore the advanced usage of local storage and how to use local storage in mobile apps.