javascript 如何附加到 HTML5 localStorage?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7679955/
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 to append to HTML5 localStorage?
提问by Lazer
I do a
我做一个
localStorage.setItem('oldData', $i("textbox").value);
to set the value of key oldData
to the value in a textbox.
将 keyoldData
的值设置为文本框中的值。
The next time something is entered to the textbox, I want to append to the already existing oldData
.
下次在文本框中输入内容时,我想附加到已经存在的oldData
.
So, if I enter applesand then orangesin my textbox, my localStorage key oldData
should look like this:
因此,如果我在文本框中输入apples和oranges,我的 localStorage 键oldData
应如下所示:
Initially:
原来:
Key | Value
---------------------------
oldData | apples
Now:
现在:
oldData | apples oranges
How can I append? Is there an append
method provided?
我怎样才能追加?有提供append
方法吗?
Or do I need to read the data first, append in javascript and then write back?
还是我需要先读取数据,在 javascript 中追加然后写回?
回答by Rob W
There's no append
function. It's not hard to write one though:
没有任何append
功能。不过写一个也不难:
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
appendToStorage('oldData', $i("textbox").value);
Note: It makes more sense to define a function append
on the localStorage
object. However, because localStorage
has a setter
, this is not possible. If you were trying to define a function using localStorage.append = ...
, the localStorage
object will interpret this attempt as "Save an object called append
in the Storage object".
注意:append
在localStorage
对象上定义一个函数更有意义。但是,因为localStorage
有setter
,这是不可能的。如果您尝试使用 定义函数localStorage.append = ...
,则该localStorage
对象会将这种尝试解释为“保存append
在存储对象中调用的对象”。
回答by Nery Jr
It is not a good solution but it works and is performative.
这不是一个好的解决方案,但它有效并且具有执行力。
localStorage.setItem("fruit", "Apples");
localStorage.setItem("fruit", localStorage.getItem("fruit") + "Orange");
回答by XCS
I found this here:
我在这里找到了这个:
interface Storage {
readonly attribute unsigned long length;
DOMString? key(unsigned long index);
getter DOMString getItem(DOMString key);
setter creator void setItem(DOMString key, DOMString value);
deleter void removeItem(DOMString key);
void clear();
};
Seems like it only has getItem,setItem,removeItem,clear,key and length.
似乎它只有 getItem、setItem、removeItem、clear、key 和 length。