How to append to HTML5 localStorage?

2019-01-23 20:32发布

I do a

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

to set the value of key oldData to the value in a textbox.

The next time something is entered to the textbox, I want to append to the already existing oldData.

So, if I enter apples and then oranges in my textbox, my localStorage key oldData should look like this:

Initially:

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

Now:

oldData  |  apples oranges

How can I append? Is there an append method provided?

Or do I need to read the data first, append in javascript and then write back?

3条回答
家丑人穷心不美
2楼-- · 2019-01-23 21:17

It is not a good solution but it works and is performative.

localStorage.setItem("fruit", "Apples"); 

localStorage.setItem("fruit", localStorage.getItem("fruit") + "Orange");
查看更多
女痞
3楼-- · 2019-01-23 21:20

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.

查看更多
别忘想泡老子
4楼-- · 2019-01-23 21:27

There's no append function. It's not hard to write one though:

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".

查看更多
登录 后发表回答