這次帶給大家Html5的localStorage使用詳解,Html5的localStorage使用注意事項有哪些,下面就是實戰案例,一起來看一下。
localStorage是Html5新加入的特性,這個特性主要用來做瀏覽器本地儲存
一、判斷瀏覽器是否支援localStorage
if (!window.localStorage) { console.log("浏览器不支持localStorage") } else { console.log("浏览器支持localStorage") }
二、往localStorage中寫入內容:
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*/
以上的程式碼的例子中:age輸入的是一個number,但是輸出時是一個string,可見localStorage只能儲存string類型的資料。
三、localStorage的刪除:
1、刪除localStorage中所有的內容:
Storage.clear() 不接受參數,只是簡單地清空網域對應的整個儲存物件。
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、刪除某個健值對:
Storage.removeItem() 接受一個參數-你想要移除的資料項的鍵,然後會將對應的資料項從網域對應的儲存物件移除。
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}
我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
#以上是Html5的localStorage使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!