本文介绍了如何附加到HTML5 localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个

  localStorage.setItem('oldData',$ i(textbox)。 

设置键 oldData 的值为文本框中的值。

下一次在文本框中输入内容时,我想追加到已存在的 oldData
因此,如果我在我的文本框中输入苹果,然后输入橙子,则我的localStorage项 oldData 应该看起来像这样:



最初:

  Key |价值
---------------------------
oldData |苹果

现在:

  oldData |苹果橙子

我该如何追加? 是否提供追加方法?



或者是否需要读取数据首先,在javascript中追加,然后回写?

解决方案

没有追加功能。尽管写一个不难:

 函数appendToStorage(name,data){
var old = localStorage.getItem (名称);
if(old === null)old =;
localStorage.setItem(name,old + data);
}

appendToStorage('oldData',$ i(textbox).value);

注意:定义一个函数 append 放在 localStorage 对象上。 然而,因为 localStorage 有一个 setter ,所以这是不可能的。如果您试图使用 localStorage.append = ... 定义一个函数,那么 localStorage 对象将解释此尝试作为在存储对象中保存名为追加的对象


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?

解决方案

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

这篇关于如何附加到HTML5 localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 17:28