简体   繁体   中英

local storage not changing the value

I am using local storage to store credentials and login details. It is working fine but when i tried to change that value it is not changing.

Here is the code for login.

login.html

 <script type="text/javascript">


                window.localStorage.setItem("login", "true");
                window.localStorage.setItem("email", data.email);
                window.localStorage.setItem("id", data.uid);    
                window.localStorage.setItem("name", data.name);                                 



</script> 

and here is the code for logout. This one not working.

logout.html

window.localStorage.setItem("login", "false");

For some reason i am always getting login = true in logout.html file.

Any advise what am i doing wrong.

Edit:

Nothing wrong with the code. It is working fine. I was accessing the file directly thats why it was not changing.

a guess: you are using somehting like

if(window.localStorage.getItem("login"))

and its true. if that is the case its because any non empty string would yield true. if that is the case, try

if(window.localStorage.getItem("login")==="true")

or

if(window.localStorage.getItem("login")!=="false")

Have you tried removing the item?

window.localStorage.removeItem("login");
window.localStorage.setItem("login", "false");

This works for me. You must have something else going on that isn't working.

<script type="text/javascript">


    localStorage.setItem("login", true); 
    alert(localStorage.getItem('login'));

    localStorage.setItem("login", false);
    alert(localStorage.getItem('login'));

</script> 

Works with quotes as well.

<script type="text/javascript">


    localStorage.setItem("login", "true"); 
    alert(localStorage.getItem('login'));

    localStorage.setItem("login", "false");
    alert(localStorage.getItem('login'));

</script> 

And here is checking...

<script type="text/javascript">


    localStorage.setItem("login", "true");

    if(localStorage.getItem("login")==="true"){
        alert('Value is True')
    }

    localStorage.setItem("login", "false");

    //login is false so this will not fire
    if(localStorage.getItem("login")==="true"){
        alert('Value is True')
    }

</script> 

perhaps, you should use

JSON.parse(localStorage.getItem("login"))

this will get your item as a boolean true or false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM