gpt4 book ai didi

javascript - 为javascript中的元素数组设置localstorage

转载 作者:行者123 更新时间:2023-11-30 11:05:07 25 4
gpt4 key购买 nike

我需要使用 vanilla JavaScript 将一组对象值设置到本地存储。

我试过遍历数组并获取每个索引然后设置每个索引它似乎不起作用。但是,如果我单独引用每个元素,它就会起作用,这很奇怪......

const theme_cache = [document.getElementById('panel').style.background,document.getElementsByClassName('icon-bar')[0].style.color]

const saved_theme_cache = JSON.parse(localStorage.getItem('cached-elements'));

element.onchange = function(){
localStorage.setItem('cached-elements', JSON.stringify(theme_cache));
}

最佳答案

localStorage 是键/值对,仅接受 strings 作为值参数。当传递其他东西时,它将调用它的 toString() 表示。您应该使用 JSON.stringify 和 JSON.parse 来序列化/反序列化该值。

const listOfTests = [{test: "test"}]
localStorage.setItem("tests", JSON.stringify(listOfTests));

const listOfTestsFromLocalStorage = JSON.parse(localStorage.getItem("tests"))

关于javascript - 为javascript中的元素数组设置localstorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com