HTML 5 本地存储入门
关于本地存储我就不做太多的介绍,以及本地存储的历史。从cookie到IE的userData再到flash然后是SQLite。他们各有优点与弊端,而如今HTML5千呼万唤始出来将它们统一了。
在HTML5中本地存储是window的属性,包括localStorage和sessionStorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了。二者用法完全相同,这里以localStorage为例。
首先,判断浏览器是否支持localStorage:
if(window.localStorage){ alert('This browser supports localStorage'); }else{ alert('This browser does NOT support localStorage'); }
存储数据的方法就是直接给window.localStorage添加属性,eg: window.localStorage.food。读操作: getItem("key"), 写操作: setItem("key",value), 删除操作: removeItem("key")。
好吧,结合例子来看看。这个例子是添加食物并保存到本地的例子
<!DOCTYPE HTML> <html> <head> <title>localstorage</title> <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> <script type="text/javascript" charset="utf-8" src="js/cordova-2.1.0.js"></script> <script type="text/javascript"> document.addEventListener("DOMContentLoaded" , function() { var foodList = document.getElementById("foodList") var foodName = document.getElementById("foodName"); // var l = window.localStorage.length , i=0 , storedFoodName; function addNewFoodItem(foodName){ var newFoodItem = document.createElement("li"); newFoodItem.innerHTML = foodName; foodList.appendChild(newFoodItem); } for(i; i<l ; ++i){ //根据键值来取值 storedFoodName = window.localStorage.key(i); if( storedFoodName.match(/^food[.]/) ) addNewFoodItem(window.localStorage.getItem(storedFoodName)); } document.getElementById("foodForm").addEventListener("submit" , function(event){ event.preventDefault(); var newFood = foodName.value , foodKey = "food."+ (window.localStorage.length +1); addNewFoodItem(newFood); window.localStorage.setItem(foodKey, newFood); foodName.value=""; return false; },false) },false); </script> </head> <body> <div id="main"> <h1>list some food</h1> <form id="foodForm"> <input type="text" id="foodName" placeholder="a name of a food"> <input type="submit" value="tell me"> </form> </div> <ul id="foodList"> </ul> </body> </html>
例子可简单了,看代码理解他们的用法吧...