如何将类似类型的多个对象添加到本地存储 [英] How do I add Multiple Objects of a similar type to local storage

查看:77
本文介绍了如何将类似类型的多个对象添加到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了几种将对象添加到此处和其他一些站点的本地存储中的解决方案,但是我的问题略有不同.我想将几个相关项目保存到本地存储中.像这样

I have seen several solutions to adding objects to local storage on here and some other sites but my problem is slightly different. I want to save several related items to local storage. Something like this

<head>
<script type="text/javascript" src="jquery.js"></script>

</head>
<body>
<input type='text' id='firstname' placeholder="first name"><br>
<input type='text' id='surname' placeholder="surname"><br>
<button id='submit'>Add</button>

<div id='displaynames'>

 <script>
$(document).ready(function(){
    $('button').click(function(){

        firstname = $('#firstname').val();
        surname = $('#surname').val();
        $('#displaynames').append("<p>"+firstname+" "+surname+"</p>");

        var names = {
            id: //what goes here?,
            name: firstname,
            lastname: surname
        };

        localStorage.setItem('names:'+counter, JSON.stringify(names));
        counter++;
        $('#displaynames').html(localStorage.getItem('names'));

    });
})   
</script>
</body>

该对象的所有属性都将由用户提供,但是没有两个对象具有相同的ID来区分它们,更重要的是,没有两个对象可以具有相同的键名,该如何实现?我的代码中某处存在某种循环?

all properties of this object will be supplied by the user but no two objects will have the same id to distinguish them and more importantly, no two object can have the same key name, how could this be implemented? some kind of loop somewhere in my code?

我希望密钥增加,例如:names:1,names:2,names:3等

I will like the key to increment like names:1, names:2, names:3 etc

推荐答案

您还可以将 counter 本身存储在localStorage中,因此每次需要添加新项时,请确保递增计数器.

Well you can also store the counter itself in the localStorage so each time you need to add a new item, you make sure to increment the counter.

// Get current counter from LS and increment it
var counter = localStorage.getItem('counter');
counter++;

// Put names in LS with a new counter id
localStorage.setItem('names:'+counter, JSON.stringify(names));

// Put back the incremented counter into LS
localStorage.setItem('counter', counter);

但是,正如注释中所建议的那样,使用一个数组来放置所有 names 会更明智.添加新名称时,其 id 可以简单地是"names:" + namesArray.length

But as suggested in a comment it would be wiser to use an array on which you put all your names. When adding a new name, its id could simply be "names:" + namesArray.length

这篇关于如何将类似类型的多个对象添加到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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