微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试从本地存储中提取保存的输入

如何解决尝试从本地存储中提取保存的输入

我在将输入文本保存到本地存储并使用 JS 检索时遇到问题。这是一个调度程序应用程序,我有多个按小时组织的输入框,用户应该能够将他们的计划输入到文本框中并保存,并且应该在页面重新加载时进行检索。 这是我的 JS:

// Add input to local storage-------------------------------------------------------//

const button = document.querySelector('.saveBtn');
const hours = ['9','10','11','12','13','14','15','16','17'];


function savePlan() {
    for (let i = 0; i < hours.length; i++) {
        // TEST: console.log(hours[i]);
        let input11 = document.getElementById('red').value;
        console.log(input11);
    };
    localStorage.setItem('plan',hours[i].value);
    // console.log(plan);
    
};

button.addEventListener('click',savePlan());

// Retrieves plan from local Storage-----------------------------------------------//
function getPlan() {
    return localStorage.getItem('plan');
};

getPlan();

这是我的 HTML 的一部分:(我在 0900-1700 小时有多个这样的框)

 <tr class="row" id="11">
            <th scope="time" id="hour11"class="time">11:00</th>
            <td><input type="text" class="textBox" id="h11input"></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>
          <tr class="row" id="12">
            <th scope="time" id="hour12" class="time">12:00</th>
            <td><input type="text" class="textBox" id="h12input"></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>

任何帮助表示赞赏。谢谢!

解决方法

当您的代码要求将对象 hours[i].value 存储到本地存储键“计划”中时,它会失败,原因有两个:

  1. “i”变量的作用域是它上面的 for 循环;循环结束,“i”将是未定义的。
localStorage.setItem('plan',hours[i]); // will write 'undefined' to local storage
  1. “hours”数组是一个字符串数组。字符串上没有“value”属性;要确认这一点,您可以尝试在 Chrome 开发工具中输入“Hello,world!”.value。您可以将“未定义”存储到本地存储中,但是您不能做的是将未定义值 (hours[i]) 上的未定义“值”属性 (.value) 的访问权限传递给 localStorage.setItem() - 这将抛出类型错误。
localStorage.setItem('plan',hours[i].value); // will throw a TypeError because it can't read a 'value' property of undefined

我不太清楚您在这里要做什么,但一些可能更接近标记的人为代码可能看起来像 this

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。