如何更改localStorage项目中的单个值? [英] How do I change a single value inside a localStorage item?

查看:1891
本文介绍了如何更改localStorage项目中的单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组保存的项目,但是在我检索它之前和我将它传递给我的php函数之前,我正试图更改一个值。是否可以只更改一个项目?

I have a set of items that get saved but I'm trying to change a value after I retrieve it and before I pass it of to my php function. Is it possible to change just one item?

我的项目字符串如下所示:

My string of items looks like this:

var args = window.localStorage.getItem("localusers");

start=0&type=1

我正在保存本地用户像这样的项目:

I'm saving the localusers item like so:

window.localStorage.setItem('localusers', $("#profile_form_id").serialize());

我正在尝试将类型的值设置为6

I'm trying to set the value of type to a 6

我找不到一个支持的方法,允许我在数组中获取/设置一个项目,所以我需要遍历数组,更改值,然后再次设置localusers项目?它似乎不是很有效但我看不到任何其他方式。

I can't find a supported method that allows me to get/set an item in the array so do I need to iterate through the array, change the value and then set the localusers item again? It doesn't seem very efficient but I can't see any other way.

有任何想法或建议吗?

推荐答案

localstorage 不返回数组或对象。它只能存储一个字符串。

localstorage does not return an array or an object. It can only store a string.

人们绕过它的方式是 JSON.stringify()数组/对象在传递给 setItem 之前。然后,当使用 getItem()检索它时,在其上运行 JSON.parse()

The way people get around it, is to JSON.stringify() the array/object before passing it to setItem. Then, when retrieving it with getItem(), you run JSON.parse() on it.

假设这是一个对象,并且你已经解析了它,你可以修改你的 args 变量,然后再发送它: / p>

Assuming this is an object, and you've parsed it, you can modify your args variable before you send it along:

args.type = 6;






为了方便这一切,这里有一个小帮手你可以打电话:


To ease all this, here's a little helper that you can call:

var localstorage = {
    set: function (key, value) {
        window.localStorage.setItem( key, JSON.stringify(value) );
    },
    get: function (key) {
        try {
            return JSON.parse( window.localStorage.getItem(key) );
        } catch (e) {
            return null;
        }
    }
};

如果包含此脚本,则可以通过 localstorage设置和获取项目.get localstorage.set ,它会自动将其转换为&来自JSON。

If you include this script, you can then set and get items through localstorage.get and localstorage.set, and it'll automatically convert it to & from JSON.

这篇关于如何更改localStorage项目中的单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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