JavaScript实现浏览器窗口复制后读取LocalStorage表单值
解决LocalStorage表单值回填问题
你现在的代码只实现了存储值到LocalStorage的逻辑,但缺少页面加载时从LocalStorage读取并回填表单的代码,另外因为用了Select2插件,直接设置下拉框选中状态需要适配插件的API,具体修改如下:
步骤1:添加页面加载时的回填逻辑
在$(document).ready函数最开始,加入读取LocalStorage并回填的代码:
$(document).ready(function() { // 页面加载时从LocalStorage读取数据并回填 const savedCruId = localStorage.getItem('cru_id'); const savedAgentName = localStorage.getItem('agent_name'); if (savedCruId) { // 找到对应CRU ID文本的option,设置选中 $('#user_list option').filter(function() { return $(this).text() === savedCruId; }).prop('selected', true); // 因为用了Select2插件,需要手动触发插件更新 $('#user_list').trigger('change.select2'); } if (savedAgentName) { // 回填代理名称到输入框 $('#agent_name').val(savedAgentName); } // 你原有的change事件逻辑保持不变 $('#user_list').change(function() { cru_id = $('#user_list').find(":selected").text(); localStorage.setItem('cru_id', cru_id); id = $(this).val(); $.ajax({ url: 'get-user-detail/' + id, type: 'get', dataType: 'json', success: function(response) { let user = response.data $("#agent_name").val(user.name); localStorage.setItem('agent_name', $("#agent_name").val()); } }) }); });
关键说明
- 你之前注释掉的读取LocalStorage的代码没有完成回填逻辑,现在补充了找到对应option并设置选中的步骤
- 因为使用了Select2插件,普通设置
prop('selected', true)后需要触发change.select2事件,否则插件不会更新显示状态 - 去掉了不必要的
JSON.stringify,因为LocalStorage存储的是字符串,直接存取即可,不需要额外序列化
这样修改后,当你打开新窗口(或刷新页面)时,LocalStorage里保存的值就会自动回填到表单中了。
内容的提问来源于stack exchange,提问作者Bilal Ahmed
相关产品推荐
相关产品推荐

