首页 文章

存储用户输入和显示

提问于
浏览
0

代码应该做的是接收用户输入并存储在LocalStorage中,然后获取已存储的输入并显示它 . 由于是localStorage,它应该保持输入并在关闭和打开后显示它 .

我跟着this tutorial并尝试修改并适合我想做的事情 . 问题是它没有保存 .

对不起,如果这是一个糟糕的问题

function saveBio() {
  var newBio = document.getElementById("bio").value; //get user input
  localStorage.setItem("storeBio", newBio); //store it

  displayBio(newBio) //take to next function
}

function displayBio(newBio) {

  document.getElementById("bio").innerHTML = localStorage.getItem("storeBio");//display the localstorge
 
}
<input id="bio" type="text" name="bio" placeholder="Bio" onmouseout=saveBio() ">

4 回答

  • 1

    像这样修复这条线:

    document.getElementById("bio").innerHTML = localStorage.getItem(newBio); // you need to get the element by providing the Id value
    

    文献 . getElementById 是一个函数,它获取Id值来查找匹配元素并返回它 . 然后,您访问该元素的 innerHTML 属性并进行更改 .

  • 0

    在你的getItem函数中,你使用了键的值来获取项目 .

    传递键名时,Storage接口的getItem()方法将返回该键的值,如果该键不存在,则返回null .

    使用 localStorage.getItem("storeBio") 而不是 localStorage.getItem(newBio)


    除此之外,你必须将你的_14914改为: document.getElementById("bio") .innerHTML .

  • 0

    您没有以正确的方式设置和获取值 .

    localStorage.setItem 接受2个参数作为输入 . (关键和 Value )
    localStorage.getItem 接受1个参数作为检索的键 .

    使用键和值设置项目,并使用您指定的键检索它 .

    Reference

  • 1

    您的代码的问题是 displayBio() 中的这一行:

    document.getElementById.innerHTML = localStorage.getItem("storeBio");
    

    你没有给出 getElementById 一个ID - 因为你想要显示生物,它应该是这样的:

    document.getElementById("bio").innerHTML = localStorage.getItem("storeBio");
    

相关问题