【问题标题】:Input not stored in local storage输入未存储在本地存储中
【发布时间】:2017-12-02 13:47:04
【问题描述】:

我在将输入从文本框存储到本地存储时遇到问题,我得到的只是“未定义”。我似乎已经按照本地存储的所有教程进行操作,但仍然无法正常工作。我有一个 index.html、app.js 和 name.js。 name.js 中的函数应该将输入存储在 app.js 中发生的点击事件上。我哪里错了?

index.html:

<form id="nameForm">
  <label>Ditt namn (Max 10 tecken):
    <input type="text" id="name" maxlength="10" />
  </label>
  <input type="button" id="submit" value="Choose" />
</form>

name.js:(它说 localStorage 没有定义)

function name () {
  let nickname = document.querySelector('#name')
  localStorage.Nickname = nickname.value
  console.log(nickname)
}

module.exports = name

app.js:

const timer = require('./timer.js')
const Quiz = require('./Quiz.js')
const name = require('./name.js')

let start = document.querySelector('#submit')
function quizAndTimer () {
  Quiz()
  timer()
  name()
}
start.onclick = quizAndTimer

【问题讨论】:

  • 你在哪里使用你的 name.js 文件?貌似是 Node 代码,但是 localStorage 对象是用来在浏览器中使用的。
  • @LucaKiebel 我在模块名称 name.js 中使用它,我将它导出并导入到 index.html 中调用的 app.js 中。这能回答问题吗?

标签: javascript dom input local-storage


【解决方案1】:

试试

localStorage.setItem('Nickname', nickname.value); // this stores 

localStorage.getItem('Nickname') // this retrieves

【讨论】:

  • 不,更改后仍未定义。
  • 我可以看到它在小提琴中运行良好,我感谢你。但即使我将您的代码复制到我的代码中,我仍然无法定义。这可能是因为我为我的页面使用了 localhost:4000 吗?
  • 但是当我使用 getElementById 而不是 querySelector 我得到了结果...
【解决方案2】:

代替:

localStorage.Nickname = nickname.value;

用途:

localStorage.setItem('NickName', nickname.value); //this sets your key/value pair in localStorage.

P.S.:localStorage 仅以键/值对和两者(键和值)格式保存 始终为字符串格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多