<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- HTML5中使用WebStorage与本地数据库来实现本地存储,不再使用cookie 使用cookie的缺陷: 大小限制在4KB cookie随http事务一起发送,占用带宽 正确操纵比较复杂 WebStorage分为两种 sessionStorage:从浏览器打开到关闭的范围内有效 localStorage:即使浏览器关闭了也有效(同一个浏览器) --> <h1>Web Storage演示</h1> <p id="msg"></p> <input type="text" id="input" /> <input type="button" value="保存数据" onclick="sessionSave('input')" /> <input type="button" value="读取数据" onclick="sessionLoad('msg')" /> <script type="text/javascript"> function sessionSave(id){ var target = document.getElementById(id); var str = target.value; sessionStorage.setItem("message",str); } function sessionLoad(id){ var target = document.getElementById(id); var msg = sessionStorage.getItem("message"); target.innerHTML = msg; } function localSave(id){ var target = document.getElementById(id); var str = target.value; localStorage.setItem("message",str); } function localLoad(id){ var target = document.getElementById(id); var msg = localStorage.getItem("message"); target.innerHTML = msg; } function localCLear(){ localStorage.clear(); alert("已清空"); } // 上面的例子比较简单,如果要保存的数据比较复杂,则可以使用JSON格式 function savePerson(id,name){ var person = new Object(); person.id = document.getElementById(id).value; person.name = document.getElementById(name).value; //对象转字符串 var personStr = JSON.stringify(person); localStorage.setItem(person.id,personStr); } function localPerson(id){ var personStr = localStorage.getItem(id); //字符串转对象 var person = JSON.parse(personStr); var id = person.id; var name = person.name; } </script> </body> </html>