首页 > 解决方案 > 如何在 localStorage 中不断更新数据?

问题描述

我一直在尝试找到一种无需刷新即可查看来自 localStorage 的新数据和更新数据的方法。我目前有一个文本框,旁边有一个提交按钮。在文本框中输入内容并单击“提交”后,您输入的文本将保存到 localStorage。然后我将其显示在文本框下方。所有这些都可以正常工作,但唯一的问题是 localStorage 中的数据不会立即显示,您必须重新加载页面。我希望数据不断更新,这样您就不必每次想要查看来自 localStorage 的数据时都重新加载页面。这是我到目前为止所拥有的:

//"saves" is the id I assigned to the div that stores the saves.
document.getElementById('saves').innerHTML = localStorage.getItem('item-array-HTML-program');

//save() gets called when the submit button is clicked.
function save() {
    //data is an empty array, and the variable "var" is the textboxes.value
    var data = [], val = document.getElementById('textbox').value;         
    //the data that's already been stored in the HTML program key gets pushed into the empty array 
    "data"
    data.push(localStorage.getItem('item-array-HTML-program'));
    //the text in the text box gets pushed into the array "data"
    data.push(val);
    //the array "data" gets set into localStorage.
    localStorage.setItem('item-array-HTML-program', data);   
}

标签: javascript

解决方案


你可以尝试这样的事情:

//at least I believe this is what you use to "render" it...
function render() {
    document.getElementById('saves').innerHTML = localStorage.getItem('item-array-HTML-program');
}


function save() {
    ...
    save code
    localStorage.setItem('item-array-HTML-program', data); 
    ...
    // once its saved, you call a render
    render()
}

抽象您需要渲染的所有代码,无论您正在渲染什么,然后在调用 save 函数后,您再次渲染它。


推荐阅读