Javascript HTML5 localStorage 将数据替换为已存在的密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3750788/
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-08-23 05:59:37  来源:igfitidea点击:

HTML5 localStorage replace data to already existing key

javascripthtmllocal-storage

提问by Mircea

I have the following localStoragekey:

我有以下localStorage键:

localStorage.setItem(1, "<div id='MyId'>value 1</div><div id='NewId'>other value</div>");

Is it possible to replace, change only the second id, make the:

是否可以替换,仅更改第二个 ID,使:

<div id='MyId'>value 1</div><div id='NewId'>other value</div>

turn into

变成

<div id='MyId'>value 1</div><div id='NewId'>replaced value</div>

I do not want to delete this key and create a new one, just replace a part of it. Thank you.

我不想删除这个键并创建一个新的,只是替换它的一部分。谢谢你。

回答by epascarello

Taken from Dive into HTML5:

摘自Dive into HTML5

Calling setItem() with a named key that already exists will silently overwrite the previous value.

使用已存在的命名键调用 setItem() 将无声地覆盖先前的值。

So read the value with getItem() [if needed], do your replace, set the new value with setItem().

因此,使用 getItem() [如果需要] 读取值,进行替换,使用 setItem() 设置新值。