Javascript 如何更改 localStorage 项目中的单个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7265028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change a single value inside a localStorage item?
提问by jQuerybeast
I'm trying to change a value inside localstorage. This item is the status of a checkbox. I want, everytime that a checkbox is checked to set the value to true or false of that checkbox. I tried many ways until I realized that there is no way you can change a value without using JSON.
我正在尝试更改 localstorage 中的值。此项是复选框的状态。我想要,每次选中复选框以将该复选框的值设置为 true 或 false 时。我尝试了很多方法,直到我意识到不使用 JSON 就无法更改值。
To add the value I use:
要添加我使用的值:
localStorage.setItem("status-" + i, $status.is(":checked"));
and to delete I use:
并删除我使用:
var parentId = $this.parent().attr('id');
localStorage.removeItem("'" + parentId + "'");
Now to change the value I tried:
现在要更改我尝试过的值:
$itemList.delegate("#status-" + i, 'click', function(e) {
var $this = $(this);
var parentId = this.parent().attr('id');
if ($this.is(":checked")) {
localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// Note that alert here works.
}
});
This is how my local storage looks like:
I hope someone could help me. I've been working on it for few days...
这就是我的本地存储的样子:
我希望有人可以帮助我。我已经研究了几天......
Thanks alot
非常感谢
回答by Joe
setItem
takes two parameters:
setItem
需要两个参数:
localStorage.setItem('status-1', "'" + parentId + "'".val("fdgsdagf"));
or more likely for your case:
或更可能为您的情况:
localStorage.setItem(parentId, "fdgsdagf");
Best Practices:
最佳实践:
localStorage.setItem('key', JSON.stringify(value));
JSON.parse(localStorage.getItem('key'));
Here's an example: http://jsfiddle.net/F8sF2/
这是一个例子:http: //jsfiddle.net/F8sF2/
EDIT: from you fiddle, you need to change:
编辑:从你的小提琴,你需要改变:
var parentId = this.parent().attr('id');
to
到
var parentId = $this.attr('id');
UPDATED http://jsfiddle.net/CC5Vw/1/
回答by ShankarSangoli
Try this
尝试这个
localStorage.setItem(parentId, "fdgsdagf");
localStorage
is nothing but JavaScript object you can treat them as associate array. So you can use them like this.
localStorage
只不过是 JavaScript 对象,您可以将它们视为关联数组。所以你可以像这样使用它们。
To set value
设定值
localStorage[parentId] = "fdgsdagf";
To get value
获取价值
var status = localStorage[parentId];