我正在制作一个疯狂的自由计划。目的是将文本输入重新加载到本地存储中,以便在重新加载页面时重建故事。
即使新输入按预期存储在本地存储中,我也无法使用新输入覆盖故事。
我需要对createStory函数做什么才能覆盖从retrieve函数生成的文本?出于某种原因,'document.getElementById(id).innerHTML = var不起作用。
Javascript:
var myStory = "A {{adjective}} {{noun}} ventured out into the world in search of {{thing}}. "
var adjective = 'adjective';
var noun = 'noun';
var thing = 'thing';
function retrieve() {
var adjective = localStorage.getItem('adjective');
var noun = localStorage.getItem('noun');
var thing = localStorage.getItem('thing');
myStory = myStory.replace(/(.*)({{adjective}})(.*)({{noun}})(.*)({{thing}})(.*)/g, '$1' + adjective + '$3' + noun + '$5' + thing + '$7');
document.getElementById('storyResult').innerHTML=myStory;
}
function createStory () {
var adjective = document.getElementById('adjective').value;
var noun = document.getElementById('noun').value;
var thing = document.getElementById('thing').value;
localStorage.adjective = document.getElementById('adjective').value;
localStorage.noun = document.getElementById('noun').value;
localStorage.thing = document.getElementById('thing').value;
myStory = myStory.replace(/(.*)({{adjective}})(.*)({{noun}})(.*)({{thing}})(.*)/g, '$1' + adjective + '$3' + noun + '$5' + thing + '$7');
document.getElementById('storyResult').innerHTML="";
document.getElementById('storyResult').innerHTML=myStory;
console.log(myStory);
};
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body onload="retrieve()">
<h1>Create a Story</h1>
<p> Adjective </p><input type="text" id="adjective">
<p> Noun</p><input type="text" id="noun">
<p> Thing </p><input type="text" id="thing">
<br><button onclick="createStory()"> Tell your tale.</button><button onclick="clear()">Clear</button>
<div id='storyResult'> </div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>