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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:55:07  来源:igfitidea点击:

How to append to HTML5 localStorage?

javascripthtmllocal-storage

提问by Lazer

I do a

我做一个

localStorage.setItem('oldData', $i("textbox").value);

to set the value of key oldDatato 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 oldDatashould look like this:

因此,如果我在文本框中输入applesoranges,我的 localStorage 键oldData应如下所示:

Initially:

原来:

Key      |   Value
---------------------------
oldData  |  apples

Now:

现在:

oldData  |  apples oranges

How can I append? Is there an appendmethod 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 appendfunction. 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 appendon the localStorageobject. However, because localStoragehas a setter, this is not possible. If you were trying to define a function using localStorage.append = ..., the localStorageobject will interpret this attempt as "Save an object called appendin the Storage object".

注意:appendlocalStorage对象上定义一个函数更有意义。但是,因为localStoragesetter,这是不可能的。如果您尝试使用 定义函数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。