首页 > 代码库 > html5 localStorage and sessionStorage
html5 localStorage and sessionStorage
<!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 =http://www.mamicode.com/ input.value; localStorage.setItem(‘name‘, value); } function get(){ //获取本地存储 var value = http://www.mamicode.com/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 =http://www.mamicode.com/ localStorage.getItem(key); list.push({‘k‘:key, ‘v‘:value}); } return list; } function showData(){ //显示所有本地存储数据 var data =http://www.mamicode.com/ 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 =http://www.mamicode.com/ input.value; sessionStorage.setItem(‘name‘, value); } function get(){ //获取本地存储 var value = http://www.mamicode.com/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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。