单个保存按钮存储多个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
相关产品推荐
相关产品推荐

