Recently has been learning HTML5, for the later mobile projects to carry out knowledge reserves. HTML5 has added some interesting tags, attributes, and methods to the HTML4, and today mainly introduces HTML5 local storage.
Store data on the client
HTML5 provides two new ways to store data on the client:
- Localstorage-Data storage with no time limit
- Sessionstorage-Data storage for session, once the window is closed there is no
Two methods are used exactly the same, the following is an example of localstorage.
Why use local storage
We used cookies in the early days, but cookies are not suitable for a large amount of data storage, that is, it is too small, only 4k in appearance, and slow and inefficient.
Localstorage method
So how do we add the data? It's simple, just like adding properties to an object:
Localstorage.pageloadcount = 1;
You can see if you have stored data through the browser's console:
It is also convenient to read and modify data:
Console.log (localstorage.pageloadcount); // Read localstorage.pageloadcount = ten; // Modify Console.log (localstorage.pageloadcount); // Read
Here are the results:
Of course localstorage itself with some methods and properties, as follows:
Localstorage.clear (); // clear all stored data localstorage.getitem (' Pageloadcount '); // read the stored data, return the value "10", equivalent to Localstorage.pageloadcountlocalstorage.key (0); // gets the key that stores the data, the return value "Pageloadcount"localstorage.length; // gets the length of the stored data localstorage.removeitem (' Pageloadcount '); // Delete specific storage data Localstorage.setitem (' name ', ' Jack '); // Add a new storage data, equivalent to Localstorage.name = ' Jack ';
It is important to note that when you read the stored data, the string is returned, regardless of what was previously saved, and the last read is a string, so the type conversion is required when reading.
Finally, the demo of Localstorage application is attached:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"/> <title>Localstorage</title></Head><Body> <PID= "P"></P></Body></HTML><Script>window.onload= function(){ if(!localstorage.pageloadcount) Localstorage.pageloadcount= 0; Localstorage.pageloadcount=parseint (Localstorage.pageloadcount)+ 1; document.getElementById ('P'). InnerHTML= 'Browse Times:' +Localstorage.pageloadcount+ 'times. ';}</Script>
Resources:
HTML 5 Web Storage
HTML5 Localstorage Local Storage