【问题标题】:Trying to pull saved input from local storage尝试从本地存储中提取保存的输入
【发布时间】:2021-10-01 11:17:58
【问题描述】:

我在将输入文本保存到本地存储并使用 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>

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

【问题讨论】:

  • 你必须把东西变成一个字符串才能把它们放到本地存储中。
  • 到底是什么问题?您执行getPlan(),但没有什么可以处理返回值。比您尝试从for 循环之外设置“计划”

标签: javascript arrays for-loop foreach local-storage


【解决方案1】:

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

  1. “i”变量的作用域是它上面的 for 循环;循环结束,“i”将未定义。
localStorage.setItem('plan', hours[i]); // will write 'undefined' to local storage
  1. “小时”数组是一个字符串数组。字符串上没有“值”属性;要确认这一点,您可以尝试在 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

【讨论】:

  • 感谢您的帮助!仍然可以进行故障排除,但可以肯定的是很好的建议,并且让我尝试了几种不同的方法。我正在制作一个日程安排应用程序,该应用程序在工作日的每个小时(0900-1700)都有文本框输入,并带有保存按钮。当按下保存按钮时,在该文本框中输入的任何内容都将保存到本地存储中,并在页面刷新时自动检索。将单个输入文本框连接到其中时遇到问题,以便保存输入的任何内容。
  • @hannahatl 我刚刚更新了答案,提供了一个超级快速和肮脏的 codepen 的链接 - 希望这能对你正在尝试做的事情有所了解
  • 哇,非常感谢您将所有这些放在一起!这绝对是有帮助的。我已经实现了你建议的代码,但它还不能很好地工作,只是将一个空数组保存到本地存储中,所以希望我可以从这里解决问题
  • 它可以工作,但只能使用保存所有按钮而不是单个按钮。仍在努力使其也与个人合作。非常感谢您的帮助!!
  • @hannahstl 请记住,在该代码中,计划优先于各个块 - 这只是一个实现细节;尝试清除计划,然后保存单个块,然后尝试遵循代码在加载、单击保存项目和单击保存计划时所采用的路径。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2021-09-29
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多