标签:
<!doctype html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="http://localhost/jquery/jquery.js"></script> </head> <body> <script> function isSupportStorage(){ return ‘localStorage‘ in window; } alert(isSupportStorage()); //判断是否支持H5本地存储 </script> <!-- ***************************localStorgae.getItem()**************************** --> <script> function set(){ //设置本地存储 var input = document.querySelector(‘#input‘); var value = input.value; localStorage.setItem(‘name‘, value); } function get(){ //获取本地存储 var value = localStorage.getItem(‘name‘); var input = document.querySelector(‘#input‘); input.value= value; } </script> <input type="text" id="input" /><br/> <button onclick="set()">保存</button> <button onclick="get()">获取</button> <!-- **************localStorage.key()***localStorage.removeItem()*************** --> <script> function listAllData(){ //获取所有本地存储数据 var list =[]; for(var i=0; i<localStorage.length; i++){ var key = localStorage.key(i); var value = localStorage.getItem(key); list.push({‘k‘:key, ‘v‘:value}); } return list; } function showData(){ //显示所有本地存储数据 var data = listAllData(); var html = ‘‘; for(var i=0; i<data.length; i++){ html += data[i].k + ‘=‘ + data[i].v + ‘<button onclick=\‘del("‘ + data[i].k + ‘")\‘>删除</button><br/>‘; } document.querySelector(‘#div‘).innerHTML = html; } function del(key){ localStorage.removeItem(key); showData(); } </script> <h3>下面是本地存储的所有数据</h3> <div id="div"> </div> <script> showData(); </script> <!-- ****************JSON.stringify()**JSON.parse()******************************* --> <script> var jsonObj = {‘id‘:123, ‘name‘:‘br‘}; function set(){ localStorage.setItem(‘json‘, JSON.stringify(jsonObj)); } function get(){ var v = JSON.parse(localStorage.getItem(‘json‘)); console.log(v); } </script> <button onclick="set()">保存</button> <button onclick="get()">获取</button> <!-- ***************************sessionStorage*********************************** --> <script> function set(){ //设置本地存储 var input = document.querySelector(‘#input‘); var value = input.value; sessionStorage.setItem(‘name‘, value); } function get(){ //获取本地存储 var value = sessionStorage.getItem(‘name‘); var input = document.querySelector(‘#input‘); input.value= value; } </script> <input type="text" id="input" /><br/> <button onclick="set()">保存</button> <button onclick="get()">获取</button> </body> </html>
html5 localStorage and sessionStorage
标签:
原文地址:http://www.cnblogs.com/oceanden/p/4248668.html