if (!window.localStorage){ alert("瀏覽器支持localstorage"); return false; }else{ //主邏輯業務 }
localStorage的寫入,localStorage的寫入有三種方法,這裏介紹一下javascript
if (!window.localStorage) { alert("瀏覽器支持localstorage"); return false; } else { var storage = window.localStorage; //寫入a字段 storage["a"] = 1; //寫入b字段 storage.a = 1; //寫入c字段 storage.setItem("c", 3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); }
這裏要特別說明一下localStorage的使用也是遵循同源策略的,因此不一樣的網站直接是不能共用相同的localStorage前端
if (!window.localStorage) { alert("瀏覽器支持localstorage"); } else { var storage = window.localStorage; //寫入a字段 storage["a"] = 1; //寫入b字段 storage.a = 1; //寫入c字段 storage.setItem("c", 3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); //第一種方法讀取 var a = storage.a; console.log(a); //第二種方法讀取 var b = storage["b"]; console.log(b); //第三種方法讀取 var c = storage.getItem("c"); console.log(c); }
這裏面是三種對localStorage的讀取,其中官方推薦的是getItem\setItem這兩種方法對其進行存取,不要問我這個爲何,由於這個我也不知道java
if (!window.localStorage) { alert("瀏覽器支持localstorage"); } else { var storage = window.localStorage; //寫入a字段 storage["a"] = 1; //寫入b字段 storage.b = 1; //寫入c字段 storage.setItem("c", 3); console.log(storage.a); // console.log(typeof storage["a"]); // console.log(typeof storage["b"]); // console.log(typeof storage["c"]); storage.a=4; console.log(storage.a); }
var storage = window.localStorage; storage.a = 1; storage.setItem("c", 3); console.log(storage); storage.clear(); console.log(storage);
var storage = window.localStorage; storage.a = 1; storage.setItem("c", 3); console.log(storage); storage.removeItem("a"); console.log(storage.a);
var storage = window.localStorage; storage.a = 1; storage.setItem("c", 3); for (var i = 0; i < storage.length; i++) { var key = storage.key(i); console.log(key); }
if (!window.localStorage) { alert("瀏覽器支持localstorage"); } else { var storage = window.localStorage; var data = { name: 'xiecanyong', sex: 'man', hobby: 'program' }; var d = JSON.stringify(data); storage.setItem("data", d); console.log(storage.data); }
var storage = window.localStorage; var data = {name: 'xiecanyong', sex: 'man', hobby: 'program'}; var d = JSON.stringify(data); storage.setItem("data", d); //將JSON字符串轉換成爲JSON對象輸出 var json = storage.getItem("data"); var jsonObj = JSON.parse(json); console.log(typeof jsonObj);