简体   繁体   中英

Saving more data to local storage

I know it is best way to use JSON but it is too complex for me to understand. Thus, may i ask is there any other ways to make sure that my data does not overwrite in local storage. Example using for loop or using another key name. Please help me by giving my examples as i am very new to HTML/JavaScript.

function saveToLS(){

    var Name = document.getElementById("rName");
    var namesaved = Name.value;
    localStorage.setItem("Name",namesaved);


    var Comment = document.getElementById("rComment");
    var commentsaved = Comment.value;
    localStorage.setItem("Comment",commentsaved);   


}

Are you going to store multiples of these? You should store them in an array or object (for example adding a timestamp id field) and store that array in LS.

The best option is using JSON. JSON is not very complex. It's just a string which is a result of stringification of a language construct like an array or object.

What you need is an array: [] , stringified version of it: "[]" . So you need to push an element into the array. How? Convert the stored JSON string into an array by parsing it, and then push an element and stringify the new array. Here is an example:

var names = localStorage.getItem("Name");
names = names ? JSON.parse(names) : [];
names.push('newName');

localStorage.setItem("Name", JSON.stringify(names));

Also don't use 2 keys for storing 2 datum that belongs to one item. It will be hard to maintain. Use an object, an array of objects:

comments.push({
  author: 'name of the author',
  comment: 'here goes the comment body...'
})

 Yeah..Me Also new In this Part... but I hope to you help full this code please try It.. var key = 0; for(key;key<10;key++){ localStorage.setItem(key, localStorage.getItem(key) + "Datas"); } 

function saveToLS(){

var Name = document.getElementById("rName");
var namesaved = Name.value;
if(localStorage.setItem("Name").length){   //the data already exists
     // Do whatever if the data already Exists......
}else{
    localStorage.setItem("Name",namesaved);
}


var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;


if(localStorage.setItem("Comment").length){ //the data already exists
     // Do whatever if the data already Exists......
}else{
    localStorage.setItem("Comment",commentsaved);
}   

}

check using localStorage.getItem(), if the data already exists and if its true don't write the data again or for that matter do whatever you want like save the data with another key

if(localStorage.setItem("Name").length){   //the data already exists
 localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
   localStorage.setItem("Name",namesaved); 
}

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