使用本地存储加载以前的输入值

时间:2014-11-27 18:41:13

标签: javascript jquery input local-storage

我正在创建一个“Mad Libs”功能,我想利用本地存储。

如果用户在输入字段中输入了值,我希望这些值保存在localStorage中......然后在重新加载页面时,这些值会加载到页面加载后生成的故事中。

JAVASCRIPT

// input references
var animalRef = document.getElementById("animal");
var nameRef = document.getElementById("name");

// local storage for each input
localStorage["animal"] = animalRef.value;
localStorage["name"] = nameRef.value;

// generate story with user inputs
var generateRef = document.getElementById("generate");
generateRef.addEventListener("click", generateStory);

function generateStory(event){
    var storyRef = document.getElementById("story");

    storyRef.innerHTML = "Once Upon a Time, there was an {{animal}} named {{name}} . . .";

    storyRef.innerHTML = storyRef.innerHTML.replace("{{animal}}", animalRef.value);
    storyRef.innerHTML = storyRef.innerHTML.replace("{{name}}", nameRef.value);
}

HTML

<div id="madLibs">
    <!-- user inputs /-->
    <b>Animal</b><br/>
    <input id="animal" placeholder="animal"/><br/>
    <b>Name</b><br/>
    <input id="name" placeholder="name"/><br/>

    <!-- button /-->
    <p align="center"><input id="generate" type="button" value="generate story"/></p>

    <hr/>

    <!-- output story /-->
    <div id="story"></div>
</div>

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

在pageleave上保存localstorage

window.onbeforeunload = function(e) {
    localStorage.setItem("animal") = animalRef.value;
    localStorage.setItem("name")   = nameRef.value;
}

检查pageload上的键

if(localStorage.getItem("animal") != null) {
    storyRef.innerHTML = storyRef.innerHTML.replace("{{animal}}", localStorage.getItem("animal"));
}
if(localStorage.getItem("name") != null) {
    storyRef.innerHTML = storyRef.innerHTML.replace("{{animal}}", localStorage.getItem("name"));
}