我知道这是使用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);
}
答案 0 :(得分:0)
你打算存储这些的倍数吗?您应该将它们存储在数组或对象中(例如添加时间戳id字段)并将该数组存储在LS中。
答案 1 :(得分:0)
最好的选择是使用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...'
})
答案 2 :(得分:0)
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");
}
答案 3 :(得分:0)
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()进行检查,如果数据已经存在,并且如果数据真实,则不再写入数据,或者为此,执行任何您想要的操作,例如使用其他密钥保存数据
if(localStorage.setItem("Name").length){ //the data already exists
localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
localStorage.setItem("Name",namesaved);
}