【问题标题】:Saving text entries to local storage in Javascript在 Javascript 中将文本条目保存到本地存储
【发布时间】:2019-03-06 16:00:47
【问题描述】:

我是 Javascript 编码的新手,我在尝试完成程序时犯了一个错误。我目前的代码是这样的:

function addTextEntry(key, text, isNewEntry) {

    // Create a textarea element to edit the entry
    var textareaElement = document.createElement("TEXTAREA");
    textareaElement.rows = 5;
    textareaElement.placeholder = "(new entry)";

    // Set the text within the textarea
    textareaElement.innerText = text;

    // Add a section to the diary containing the textarea
    addSection(key, textareaElement);

    // If this is a new entry (added by the user clicking a button)
    // move the focus to the text area to encourage typing
    if (isNewEntry) {
      textareaElement.focus();
    }

    // TODO: Q1(c)(iii)
    // TODO: Add an event listener to textareaElement to save the text when 
 it changes
    textareaElement.addEventListener("change", function(event) {
      // TODO: Within the listener function...
      // TODO: ...make an item using the text area value
      item = makeItem(
      "text",
      textareaElement.value
    );
      // TODO: ...store the item in local storage using the given key
       localStorage.setItem(key, item);
       });
}

正如编码 cmets 中所述,我的目标是在本地存储中制作和存储项目,但这不起作用。我知道这很可能是用户错误,因为无法理解我应该在 (localStorage.setItem) 行中指的是什么“键”。抱歉,如果这是一个愚蠢的错误或不合逻辑的错误,我仍在学习,所以我无法理解我做错了什么。

我的 HTML 代码如下,如有必要,我可以添加其余的 Javascript 代码:

我的 Erehwon 日记 rw9438

<main>
  <section id="text" class="button">
    <button>Add entry</button>
  </section>
  <section id="image" class="button">
    <button>Add photo</button>
    <input type="file" accept="image/*">
  </section>
</main>

【问题讨论】:

  • “无法理解我应该指的是什么‘键’”您当前使用的是什么键?

标签: javascript html function key local-storage


【解决方案1】:

localStorage 只能存储一个字符串作为它的值。您正在尝试将值设置为对象。

您可以只存储 texarea 中的文本

localStorage.setItem(key, textareaElement.value)

或者如果你真的想存储一个对象,你必须将它字符串化

localStorage.setItem(key, JSON.stringify(item))

当您从 localStorage 检索“项目”时,不要访问 JSON.parse

【讨论】:

  • 如何获取新的setItem
【解决方案2】:

没什么大不了的,没错,这很愚蠢:)

您所指的键值,现在是函数中的键参数:addTextEntry(key, text, isNewEntry)key 的命名并不重要,但为了确定它的含义,您可以尝试在您的 localStorage.setItem 下方添加 console.log(localStorage) 声明。因此,您可以检查它存储在 localStorage 对象中的内容,并检查存储值的键。

这是来自浏览器控制台的示例,其中的键是myKey

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2019-03-31
    • 1970-01-01
    • 2018-11-05
    • 2017-03-19
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多