HTML5 web Storage存储-localStorage 与 sessionStorage 案例记录用户名密码

时间:2022-12-22 19:46:22
1. storage的特性:
        a) 设置、读取方便;容量较大;
        b) 只能存储字符串,可以将对象JSON.stringify()编码后存储
2. localStorage.getItem() 
        a) 20M 永久本地存储 需要手动删除,
        b) 可以多个窗口共享
3. sessionStorage.getItem()
        a) 5M 关闭浏览器就会删除数据,
        b) 同一个窗口下数据可以共享
4. 方法对象:
        a) *.setItem(key,value) 存储数据、
        b) *.getItem(key) 获取数据、
        c) *.removeItem(key) 删除数据

        d) *.clear() 清空所有数据

记录用户名与密码


<label>用户名:<input type="text" class="userName"></label><br>
<label>&nbsp;&nbsp;&nbsp;码:<input type="password" class="pwd"></label><br>
<!--<label><input type="checkbox" class="check" checked>记住密码</label><br>-->
<label><input type="checkbox" class="check">记住密码</label><br>
<button>登录</button>

<script>
    (function(){
        var userName=document.querySelector('.userName');
        var pwd=document.querySelector('.pwd');
        var check=document.querySelector('.check');
        var aBtn=document.querySelector('button');

        aBtn.addEventListener('click',function(){
            if(check.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');
        }

    })();
</script>
<label>用户名: <input type= "text" class= "userName" ></label><br> <label>&nbsp;&nbsp;&nbsp;码: <input type= "password" class= "pwd" ></label><br> <!--<label><input type="checkbox" class="check" checked>记住密码</label><br>--> <label><input type= "checkbox" class= "check" >记住密码 </label><br> <button>登录 </button> <script> ( function(){ var userName= document. querySelector( '.userName') ; var pwd= document. querySelector( '.pwd' ) ; var check= document. querySelector( '.check') ; var aBtn= document. querySelector( 'button') ; aBtn. addEventListener( 'click' , function(){ if( check. 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') ; } })() ; </script>