You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单个保存按钮存储多个input到localStorage时首个输入无法保存的原因

问题原因分析

你遇到的核心问题是重复定义了同名函数:

  • 你写了两个init函数,第二个会覆盖第一个,页面加载时只会执行第二个init,所以第一个输入框的本地缓存不会被读取
  • 同样写了两个onSavePressed函数,第二个覆盖第一个,点击保存按钮时只会执行第二个函数,只保存第二个输入框的值
修正后的代码

HTML部分(无需修改)

<body onload="init()">
    <input type="text" id="myTxt1" placeholder="Type here ..." ></br></br></br>
    <input type="text" id="myTxt2" placeholder="Type here ..."></br></br>
    <button onclick="onSavePressed()">Save</button>
</body>

JavaScript部分(合并同名函数)

function init(){
    // 加载第一个输入框的缓存
    if (localStorage.first1Box){
        document.getElementById("myTxt1").value = localStorage.first1Box;
    }
    // 加载第二个输入框的缓存
    if (localStorage.second2Box){
        document.getElementById("myTxt2").value = localStorage.second2Box;
    }
}

function onSavePressed(){
    // 保存第一个输入框的值
    localStorage.first1Box = document.getElementById("myTxt1").value;
    // 保存第二个输入框的值
    localStorage.second2Box = document.getElementById("myTxt2").value;
    alert("Saved Successfully!!!");
}
补充说明
  • JavaScript中,同一作用域下的同名函数会被后面的定义完全覆盖,前面的函数代码会被忽略
  • 如果需要处理多个元素的逻辑,应该把相关代码合并到同一个函数里,而不是重复定义同名函数

内容的提问来源于stack exchange,提问作者Evelina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:30:53