How to append to HTML5 localStorage?

前端 未结 3 1224
情书的邮戳
情书的邮戳 2020-12-15 14:08

I do a

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

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

相关标签:
3条回答
  • 2020-12-15 14:22

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

    0 讨论(0)
  • 2020-12-15 14:37

    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.

    0 讨论(0)
  • 2020-12-15 14:40

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

    localStorage.setItem("fruit", "Apples"); 
    
    localStorage.setItem("fruit", localStorage.getItem("fruit") + "Orange");
    
    0 讨论(0)
提交回复
热议问题