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

Trying to pull saved input from local storage

我无法将输入文本保存到本地存储并使用 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 存储到本地存储键 'plan' 时,它会失败,原因有两个:

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

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