问题描述
我做了一个
localStorage.setItem('oldData',$ i(textbox)。
设置键 oldData
的值为文本框中的值。
下一次在文本框中输入内容时,我想追加到已存在的 oldData $ c
因此,如果我在我的文本框中输入苹果,然后输入橙子,则我的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 $ c更有意义$ c>放在
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!