如何从localStorage中稳定显示用户表单提交的数据?
解决方法
核心问题分析
数据显示后快速消失的原因是表单默认提交行为会触发页面刷新,同时当前代码的store()函数在页面加载时就执行,此时用户还未输入内容,且没有绑定到正确的触发时机上。
具体修复步骤
1. 阻止表单默认提交刷新
给表单添加onsubmit事件,阻止页面刷新行为。
2. 添加提交按钮绑定存储逻辑
新增按钮让用户主动触发数据存储,避免无意义的页面加载时执行存储。
3. 页面加载时自动读取已有数据
页面打开时直接从localStorage读取历史数据并显示,保证刷新后数据不丢失。
修改后的完整代码
<!DOCTYPE html> <html> <body> <!-- 阻止表单默认提交刷新 --> <form style="width:50%; margin-left: 20%; margin-top: 1.9%;" onsubmit="return false;"> <div class="form-group mx-sm-3 mb-2"> <h2 style="font-size: 1.0rem;">Selecione a data</h2> <input id="datepicker" width="396" /> <div class="input-group mb-3"> <input type="text" class="form-control" id="matriz" aria-label="Amount (to the nearest dollar)"> <div class="input-group-append"> <span class="input-group-text">Matriz</span> </div> </div> <div class="input-group mb-3"> <input type="text" class="form-control" id="rep" aria-label="Amount (to the nearest dollar)"> <div class="input-group-append"> <span class="input-group-text">Rep</span> </div> </div> <!-- 添加提交按钮触发存储 --> <button type="button" onclick="store()" class="btn btn-primary">Salvar</button> </div> <p>Saved info is:</p> <p id="currentDate"></p> <p id="currentRep"></p> <p id="currentMatriz"></p> </form> <script> $('#datepicker').datepicker({ uiLibrary: 'bootstrap5' }); // 页面加载时自动读取localStorage数据显示 window.onload = function() { document.getElementById("currentDate").innerHTML = localStorage.getItem("Date") || ""; document.getElementById("currentRep").innerHTML = localStorage.getItem("Rep") || ""; document.getElementById("currentMatriz").innerHTML = localStorage.getItem("Matriz") || ""; }; function store(){ const inputDate = document.getElementById('datepicker').value; const inputRep = document.getElementById('rep').value; const inputMatriz = document.getElementById('matriz').value; window.localStorage.setItem('Date', String(inputDate)); window.localStorage.setItem("Rep", String(inputRep)); window.localStorage.setItem("Matriz", String(inputMatriz)); // 直接用输入值更新显示,无需重复读取localStorage document.getElementById("currentDate").innerHTML = inputDate; document.getElementById("currentRep").innerHTML = inputRep; document.getElementById("currentMatriz").innerHTML = inputMatriz; } </script> </body> </html>
关键修改说明
onsubmit="return false;":彻底阻止表单提交时的页面刷新,避免数据显示后被清空。- 新增提交按钮:让用户主动触发数据存储逻辑,符合交互习惯。
window.onload事件:页面初始化时自动加载历史数据,刷新页面后数据仍能稳定显示。- 存储后直接用输入值更新显示:减少一次
localStorage读取操作,提升效率。
内容的提问来源于stack exchange,提问作者user19270359
相关产品推荐
相关产品推荐

