[英]Saving more data to local storage
我知道這是使用JSON的最佳方法,但是對我來說太復雜了。 因此,請問還有其他方法可以確保我的數據不會在本地存儲中被覆蓋。 使用for循環或使用另一個鍵名的示例。 請舉我的示例來幫助我,因為我是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);
}
您要存儲這些的倍數嗎? 您應該將它們存儲在數組或對象中(例如,添加時間戳記ID字段),然后將該數組存儲在LS中。
最好的選擇是使用JSON。 JSON不是很復雜。 它只是一個字符串,是字符串(如數組或對象)的語言結構字符串化的結果。
您需要一個數組: []
,它的字符串化版本: "[]"
。 因此,您需要將元素推入數組。 怎么樣? 通過解析存儲的JSON字符串將其轉換為數組,然后推送一個元素並對新數組進行字符串化。 這是一個例子:
var names = localStorage.getItem("Name");
names = names ? JSON.parse(names) : [];
names.push('newName');
localStorage.setItem("Name", JSON.stringify(names));
也不要使用2個鍵來存儲屬於一項的2個基准。 這將很難維護。 使用一個對象,一個對象數組:
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);
}
}
使用localStorage.getItem()檢查數據是否已經存在,如果數據為true,則不要再次寫入數據,或者執行任何操作,如使用另一個鍵保存數據
if(localStorage.setItem("Name").length){ //the data already exists
localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
localStorage.setItem("Name",namesaved);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.