<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>localStorage</title> </head> <body> <h2>localStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="getData()">点我读取一个数据</button> <button onclick="delData()">点我删除一个数据</button> <button onclick="clearData()">点我清空所有数据</button> <script type="text/javascript"> // 保存数据,浏览器关闭,数据也在 function saveData(){ //key 和 value均为字符串 window.localStorage.setItem('msg','hello!') localStorage.setItem('msg2',666)//会自动转成字符串存储 let p = {name:'张三',age:20} localStorage.setItem('msg3',JSON.stringify(p))//会自动转成字符串存储 } function getData(){ // 读取数据 const msg3 = localStorage.getItem('msg3') console.log(msg3); } function delData(){ // 删除数据 localStorage.removeItem('msg2') } function clearData(){ // 清空数据 localStorage.clear() } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>sessionStorage</title> </head> <body> <h2>sessionStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="getData()">点我读取一个数据</button> <script type="text/javascript"> // 保存数据,数据只保存在一次会话中 function saveData(){ //key 和 value均为字符串 window.sessionStorage.setItem('msg','hello!') sessionStorage.setItem('msg2',666)//会自动转成字符串存储 let p = {name:'张三',age:20} sessionStorage.setItem('msg3',JSON.stringify(p))//会自动转成字符串存储 } function getData(){ // 读取数据 const msg3 = sessionStorage.getItem('msg3') console.log(msg3); } </script> </body> </html>
标签:function,储存,浏览器,msg3,sessionStorage,setItem,localStorage,本地,数据 From: https://www.cnblogs.com/ixtao/p/17498500.html