简体   繁体   中英

LocalStorage data get cleared after refreshed and click button

I am create a employee array object which consist of 4 arrays. I am trying to add new array in every 2 seconds after clicking on start button. I want it to end at 8th position. Everything is working fine here.

But if I refresh the page and click on the start button it get start from the beginning. Why clicking on start button is clearing the localStorage Data?

demo URL

My code seem to be big but it is dong very small stuff. Explaining code step by step.

1) First I create Employees array.

2) Push data into employees array.

3) localStorage SetItem

4) Get Item

5) onclick getitems to document on setinterval.

6) stop if the length of employee is 8

I hope it helps.

JS code to setItems to localstorage and get

function set_and_increase_localstorage_data(){
    employees.push(employees[3]);
    update_array();
    localStorage.setItem("empData", JSON.stringify(employees));
    var len = employees.length;
    console.log(len)
    if(len===8 || len>=8){
        window.clearInterval(setInt);
    }   

    getEmpdata();


}
function getEmpdata(){

    myJsonData = localStorage.getItem("empData");
    if(myJsonData){
        var myData = JSON.parse(myJsonData);
        var oblen = myData.length;
        console.log("JS object stored in localstorage: " + oblen);

        //setItem to localstorage
        if(myJsonData){
            // JSON data into javascript object
            var output = "<div class='wrapper'>";
            for(var i=4;i<myData.length;i++){
                output += "<div class='item'>" + myData[i].name + "</div>";
            }
            output += "</div>";
        }

        document.getElementById('json_data').innerHTML = output;

    }
}

加载页面时,用于写入localStorageemployees变量始终加载新数据 - 您永远不会将本地存储中的数据读回employees

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