Home > Article > Web Front-end > Detailed explanation of the use of localStorage in Html5
This time I will bring you a detailed explanation of the use of localStorage in Html5. What are the precautions for using localStorage in Html5?The following is a practical case, let's take a look.
localStorage is a newly added feature of Html5. This feature is mainly used for browser local storage1. Determine whether the browser supports localStorageif (!window.localStorage) { console.log("浏览器不支持localStorage") } else { console.log("浏览器支持localStorage") }2. Go to localStorage Write content:
var DemoStorage = window.localStorage; //写入方法1: DemoStorage.name = "Tom"; //写入方法2: DemoStorage["age"] = 18; //写入方法3: DemoStorage.setItem("hobby", "sport"); console.log(DemoStorage.name,typeof DemoStorage.name); console.log(DemoStorage.age, typeof DemoStorage.age); console.log(DemoStorage.hobby, typeof DemoStorage.hobby); /*输出结果: Tom string 18 string sport string*/In the above code example: age input is a number, but the output is a string. It can be seen that localStorage can only store string type data. 3.
Delete of localStorage:
1. Delete all contents in localStorage: Storage.clear() does not accept parameters, just simple Clear the entire storageobject corresponding to the domain name.
var DemoStorage = window.localStorage; DemoStorage.name = "Tom"; DemoStorage.age = 18; DemoStorage.hobby = "sport"; console.log(DemoStorage); //输出:Storage {age: "18", hobby: "sport", name: "Tom", length: 3} DemoStorage.clear(); console.log(DemoStorage); //输出: Storage {length: 0}2. Delete a key-value pair: Storage.removeItem() accepts a parameter - the key of the data item you want to remove, and then the corresponding data item will be Removed from the storage object corresponding to the domain name.
var DemoStorage = window.localStorage; DemoStorage.name = "Tom"; DemoStorage.age = 18; DemoStorage.hobby = "sport"; console.log(DemoStorage); //输出:Storage {age: "18", hobby: "sport", name: "Tom", length: 3} DemoStorage.removeItem("age"); console.log(DemoStorage); //输出:Storage {hobby: "sport", name: "Tom", length: 2}I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
JavaScript code for hiding elements one by one
detailed explanation of javscript’s callback function
The above is the detailed content of Detailed explanation of the use of localStorage in Html5. For more information, please follow other related articles on the PHP Chinese website!