初识 localStorage-1与 初识localStorage-2

初识 localStorage-1

     1.localStorage是什么

        localStorage 也是一种浏览器存储数据的方式(本地存储),它只是存储在本地,不会发送到服务器端

        单个域名下的localStorage总大小有限制 

        2.在浏览器中操作localStorage

     3.localStorage的基本用法

      

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>初始localStorage</title>
    </head>
    <body>
       <script>
            //console.log(localStorage)
            
            //setItem()存储数据
            localStorage.setItem('username','lyw');
            localStorage.setItem('username','yth');
            localStorage.setItem('age',18);
            localStorage.setItem('sex','nv');
            
            //length
            //console.log(localStorage.length)
            
            //getItem
            /* console.log(localStorage.getItem('username'));
            console.log(localStorage.getItem('age'));
            console.log(localStorage.getItem('sex')); */
            
            //获取不存在的返回null
            console.log(localStorage.getItem('name'));
            //console.log(localStorage);
                
            
            //removeItem
            /* localStorage.removeItem('username');
            localStorage.removeItem('age');    
            //删除不存在的key,不报错
            localStorage.removeItem('name');     */
            
            //clear()
            localStorage.clear();      
                
            

            console.log(localStorage)                
       </script>
    </body>
</html>

 

      

 

 

       

 

 

       

 

 

       

 

      

       

     

初识localStorage-2

     .使用localStorage实现自动填充

     

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>初始localStorage</title>
    </head>
    <body>
        <form id="login" action="https://www.baidu.com" method="post">
            <input type="text" name="username" />
            <input type="password" name="password"/>
            <input type="submit" id="btn" value="登录"/>
        </form>
       <script>
            
            //4.使用localStorage实现自动填充 
            const loginForm = document.getElementById('login');
            const btn =document.getElementById('btn');
            
            const username = localStorage.getItem('username');
            if(username){
                loginForm.username.value = username;
            }
            
            btn.addEventListener(
            'click',
              e=> {
                  e.preventDefault();
                  //数据验证
                  //console.log(loginForm.username.value);
                  
                  localStorage.setItem('username',loginForm.username.value);
                  
                  loginForm.submit();
            },
              false       
            );
       </script>
    </body>
</html>

 

       

 

         

      

 

posted @ 2023-03-22 09:23  zj勇敢飞,xx永相随  阅读(83)  评论(0编辑  收藏  举报