在html5之前,浏览器要实现数据的存储,一般都是用cookie,但是cookie有域名和大小限定.
html5流行之后,可以通过localStorage和sessionStorage实现浏览器端的数据存储,这两者有什么特点呢?
sessionStorage
sessionStorage属于临时会话,数据存储的有效期为:从页面打开到页面关闭的时间段,属于窗口的临时存储,页面关闭,本地存储消失
localStorage
sessionStorage的应用:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function(){ 8 var aInput = document.getElementsByTagName('input'); 9 aInput[0].onclick = function(){ window.sessionStorage.setItem("name", aInput[3].value ); 12 }; 13 aInput[1].onclick = function(){ 14 alert(window.sessionStorage.getItem("name" )); 15 }; 16 aInput[2].onclick = function(){ 17 window.sessionStorage.removeItem("name" ); 18 }; 19 } 20 </script> 21 </head> 22 <body> 23 <input type="button" value="设置" /> 24 <input type="button" value="获取" /> 25 <input type="button" value="删除" /> 26 <br/> 27 <input type="text" /> 28 </body> 29 </html>
localStorage的应用
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function(){ 8 var aInput = document.getElementsByTagName('input'); 9 aInput[0].onclick = function(){ window.localStorage.setItem("name", aInput[3].value); 12 window.localStorage.setItem("name2", 'aaaaa'); 13 }; 14 aInput[1].onclick = function(){ 15 alert( window.localStorage.getItem( "name" ) ); 16 alert( window.localStorage.getItem( "name2" ) ); 17 }; 18 aInput[2].onclick = function(){ 19 window.localStorage.removeItem("name"); }; 22 } 23 </script> 24 </head> 25 <body> 26 <input type="button" value="设置" /> 27 <input type="button" value="获取" /> 28 <input type="button" value="删除" /> 29 <br/> 30 <input type="text" /> 31 </body> 32 </html>
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 window.onload = function () { 8 var aInput = document.getElementsByTagName("input"); 9 var oT = document.querySelector("textarea"); (window.localStorage.getItem("userName")) { 12 aInput[0].value = window.localStorage.getItem("userName"); 13 } (var i = 0; i < aInput.length; i++) { 16 if (window.localStorage.getItem('sex') == aInput[i].value) { 17 aInput[i].checked = true; 18 } 19 } (window.localStorage.getItem("note")) { 22 oT.value = window.localStorage.getItem("note"); 23 } 24 25 window.onunload = function () { 26 if (aInput[0].value) { 27 window.localStorage.setItem("userName", aInput[0].value); 28 } (var i = 0; i < aInput.length; i++) { 31 if (aInput[i].checked == true) { 32 window.localStorage.setItem('sex', aInput[i].value); 33 } 34 } (oT.value) { 37 window.localStorage.setItem('note', oT.value); 38 } 39 } 40 } 41 </script> 42 </head> 43 <body> 44 <p> 45 用户名: <input type="text"/> 46 </p> 47 48 <p> 49 性别: <br/> 50 <input type="radio" value="男"/>男 51 <input type="radio" value="女"/>女 52 </p> 53 54 <p> 55 备注: 56 <textarea cols="30" rows="10"></textarea> 57 </p> 58 59 </body> 60 </html>