javascript - 如何在 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);
}
解决方案
你可以尝试这样的事情:
//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 函数后,您再次渲染它。
推荐阅读
- flutter - Flutter - 将小部件提升到其他小部件之上
- mysql - 备份数据库时不存在 getaccountname 错误
- typescript - 是否可以使用函数参数的名称作为接口的属性来动态键入函数的输出?
- javascript - $.post 不是 Php Ajax 中的函数
- c# - 为什么 My End Bracket 在 unity 2018.14 中出现错误
- java - 缺少工件 org.eclipse.persistence:org.eclipse.persistence.moxy:jar:2.7.3
- artifactory - 如何将 RPM repodata 正确部署到 Artifactory?
- python - 在 Ursina 模块中调用()做什么
- amazon-web-services - 使用预签名 URL 上传到 S3 存储桶会出现 403 禁止错误
- java - Java中的猪拉丁语翻译器不起作用?