The difference between cookie, sessionstorage and localstorage

1. The storage location is different.
Cookies are transferred back and forth between the browser and the server
. Sessionstorage is stored locally.
2. The storage size is different.
Cookies can generally only store 4K.
Sessionstorage and localstorage can store less than 5M
. 3. The data validity period is different.
Cookies can be set in Sessionstorage is valid until the expiration time.
Sessionstorage is valid until the browser is closed. Localstorage is always valid.
4. Cookies with different scopes.
Localstorage shares
sessionstorage in all windows of the same origin. It is not compatible with different browsers, even on the same page.

It is common to encounter that after entering a username once on a website, it will be recorded. How to do this?
After understanding the above, you can try the following case.
Name it "My Name"

    <button>点击</button>
    <input type="text" class="ipt">
    <input type="text" id="username"><input type="checkbox" name="" id="remember">我的名字
        var username=document.querySelector('#username');
        var remember=document.querySelector('#remember');
        var btn=document.querySelector('button');
        var ipt=document.querySelector('.ipt');
        btn.addEventListener('click',function(){
    
    
            var val=ipt.value;
            localStorage.setItem('username',val);
        })
        if(localStorage.getItem('username')){
    
    
            username.value = localStorage.getItem('username');
            remember.checked=true;
        }
        remember.addEventListener('change',function(){
    
    
            if(this.checked){
    
    
                localStorage.setItem('username',username.value)
            }else{
    
    
                localStorage.removeItem('username')
            }
        })

Enter your name in one input box, and after refreshing, it will be displayed in the second input box. It is
Insert image description here
very user-friendly.

Guess you like

Origin blog.csdn.net/qq_48439911/article/details/124534915