简体   繁体   English

如何检索以前的localStorage值?

[英]How do I retrieve previous localStorage value?

This is my code... 这是我的代码...

function sendit() {
/*SEND DATA TO LOCAL STORAGE*/
    var mobject = { 'yes': 1};      
    $('.yes').on('click',function() {
            mobject.yes++;
            localStorage.setItem('mobject', JSON.stringify(mobject));
            var retrievedObject = localStorage.getItem('mobject');
            console.log('retrievedObject: ', JSON.parse(retrievedObject));
    });//end click
/**/
}//end yes

The results show up fine as I am clicking on my page and checking out the console log. 当我单击页面并检出控制台日志时,结果显示良好。 But if I was to refresh the page, what must I change in my code to start the numerical value from where I left off? 但是,如果要刷新页面,我必须在代码中进行哪些更改才能从中断处开始数值?

Do a check on the local storage variable to see if it exists. 检查本地存储变量是否存在。 If it does set mobject to that value else set to your default: 如果确实将mobject设置mobject值,则将其设置为默认值:

function sendit() {
/*SEND DATA TO LOCAL STORAGE*/
    var mobject = localStorage.getItem('mobject') ? JSON.parse(localStorage.getItem('mobject'))  : { 'yes': 1};      
    $('.yes').on('click',function() {
            mobject.yes++;
            localStorage.setItem('mobject', JSON.stringify(mobject));
            var retrievedObject = localStorage.getItem('mobject');
            console.log('retrievedObject: ', JSON.parse(retrievedObject));
    });//end click
/**/
}//end yes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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