【问题标题】:How to have constantly updated data in localStorage?如何在 localStorage 中不断更新数据?
【发布时间】:2021-06-22 10:33:15
【问题描述】:

我一直在尝试寻找一种无需刷新即可查看来自 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);   
}

【问题讨论】:

  • 这很混乱,请添加HTML Body部分!
  • 您可以在您使用的任何输入上绑定onChange 处理程序,这将更改将调用save()的数据

标签: javascript


【解决方案1】:

你可以试试这样的:

//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()
}

提取所有需要渲染的代码,然后在调用保存函数后再次渲染它。

【讨论】:

    【解决方案2】:

    您只更新“保存”值一次

    主要问题是您只更新“保存”容器值一次,即页面加载时(第 2:4 行),这就是为什么您在单击“保存”按钮时看不到它更新的原因。

    因此,为了查看“实时”更新,您需要在每次保存新容器时更新“保存”容器值。

    最佳做法

    1. 尽量少查询“文档”对象。使用您需要的对象的 HTML 引用创建全局变量应该可以完成这项工作。

    2. 正如BrunoNoriller 建议的那样,我将创建一个单独的render() 函数来防止代码重复并提高可维护性

    3. 创建尽可能少的变量,你可以直接用你想要的值初始化数组“val”。这在小型应用程序中可能无关紧要,但可以对中型/大型应用程序的可维护性产生很大影响。

    var display = document.getElementById('saves') // ¹
    var textbox = document.getElementById('textbox') // ¹
    var lsname = 'item-array-HTML-program'
    
    // Updates the inner value of the 'saves' container ²
    function render() {
      display.innerHTML = localStorage.getItem(lsname); 
    }
    
    // Save new data to localStorage and re-render
    function save() {
        var data = [
          localStorage.getItem(lsname), // Single variable with both textbox
          textbox.value                 // and localStorage values ³
        ]
        localStorage.setItem(lsname, data); 
        render()
    }
    
    // Render the current value of localStorage when the page loads
    render()
    

    我知道这比你要求的要多,但我希望我能以某种方式帮助你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-12
      • 2015-10-21
      • 2019-03-24
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      相关资源
      最近更新 更多