localStorage不断覆盖我的数据 [英] localStorage Keeps Overwriting My Data

查看:624
本文介绍了localStorage不断覆盖我的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将下拉框中的值保存到localStorage中.但是,我不希望下次用户从下拉菜单中选择新信息时,数据会被新信息覆盖.我只想继续为我的localStorage增加价值而不覆盖它.任何帮助将不胜感激.

I am saving values from my dropdown box into localStorage. However, I don't want the data to be overwritten with the new info the next time user choose from the dropdown menu. I just want to keep adding value to my localStorage without it overwriting. Any help will be appreciated.

JavaScript代码:

JavaScript code:

function reason(){
        var dropd = document.getElementById("savedrop").value;
        var drophistory = JSON.parse(localStorage.getItem("savedrop"));
        localStorage.setItem("reason", JSON.stringify(dropd));
    }

HTML代码:

<select id="savedrop">
                    <option value="" disabled="disabled" selected="selected">Please choose one</option>
                    <option value="one">1</option>
                    <option value="two">2</option>
                    <option value="three">3</option>
                </select>
<input id="btnbutton" class="btn" type="button" onClick="reason()" value="Submit">

推荐答案

localStorage中,数据保存在字符串的键值对中. 每次调用setItem()时,它将添加或覆盖现有值.而getItem()只是获取存储在localStorage中的值为字符串值.为了解决这个问题,您必须使用一个数组,stringify,然后将其存储. 下面是正确的代码:

In localStorage data is saved in key value pairs of strings. Each time you call setItem() it will add or overwrite existing value. And getItem() just fetches the value stored in localStorage which is a string value. To solve this you have to use an array, stringify it and then store it. Below is the correct code:

function reason(){
    var dropd = document.getElementById("savedrop").value;
    var drophistory = JSON.parse(localStorage.getItem("reason")) || [];
    drophistory.push(dropd);
    localStorage.setItem("reason", JSON.stringify(drophistory));
}

这篇关于localStorage不断覆盖我的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆