Home > Article > Web Front-end > html5web storage example code
In the past, we used document.cookie to store data locally. However, because its storage size is only about 4K, the analysis is also very complicated, which brings problems to development. It has caused a lot of inconvenience. But now html5 has web storage, which makes up for the shortcomings of cookies, and it is also quite convenient to open.
Web storage is divided into two categories
sessionStorage
The capacity is about 5M, and the life cycle of this method is until the browser window is closed
localStorage
The capacity is about 20M. The stored data will not expire when the user's browsing session expires, but will be deleted at the user's request. Browsers also delete them due to storage space limitations or security reasons. And the data stored by the type can be shared by multiple windows of the same browser.
Note: Only strings can be stored, if it is a json object, You can encode the object JSON.stringify() and store it. Detailed explanation of the method:
setItem(key, value) 设置存储内容 getItem(key) 读取存储内容 removeItem(key) 删除键值为key的存储内容 clear() 清空所有存储内容
Let’s show you how to write it:
//更新 function update() { window.sessionStorage.setItem(key, value); } //获取 function get() { window.sessionStorage.getItem(key); } //删除 function remove() { window.sessionStorage.removeItem(key); } //清空所有数据 function clear() { window.sessionStorage.clear(); }
If there is an old version, there is no Application, and the old version is
ResourceI will show you the classic example of recording username and password
When the
checkbox for remember passwordis checked, the username and password do not need to be re-entered the next time you open it HTML part:
<label for=""> 用户名: <input type="text" class="userName"/> </label> <br/><br/> <label for=""> 密 码: <input type="password" class="pwd"/> </label> <br/><br/> <label for=""> <input type="checkbox" class="ckb"/> 记住密码 </label> <br/><br/> <button>登录</button>
js part
var userName=document.querySelector('.userName'); var pwd=document.querySelector('.pwd'); var sub=document.querySelector('button'); var ckb=document.querySelector('.ckb'); sub.onclick=function(){ // 如果记住密码 被选中存储,用户信息 if(ckb.checked){ window.localStorage.setItem('userName',userName.value); window.localStorage.setItem('pwd',pwd.value); }else{ window.localStorage.removeItem('userName'); window.localStorage.removeItem('pwd'); } // 否则清除用户信息 } window.onload=function(){ // 当页面加载完成后,获取用户名,密码,填充表单 userName.value=window.localStorage.getItem('userName'); pwd.value=window.localStorage.getItem('pwd'); }
[Related recommendations]
1.
Free h5 online video tutorialHTML5 full version manualphp.cn original html5 video tutorialThe above is the detailed content of html5web storage example code. For more information, please follow other related articles on the PHP Chinese website!