生成简单的疯狂自由

时间:2016-12-08 03:24:36

标签: javascript html innerhtml var

我正在尝试使用Javascript创建一个非常简单的疯狂lib。我大部分时间都已完成,但我的代码无法运行。是否有我忘记添加或添加不当的内容?

HTML:

   <body>
  <h1>Mad Libs</h1>

<div id="story">
  <p>A thing:</p>
    <input type="text" id="thing">
  <p>A name:</p>
    <input type="text" id="title">
  <p>An adjective ending in "ily":</p>
    <input type="text" id="adjective">
  <p>A name:</p>
    <input type="text" id="noun">
</div>

<br/>

  <button id="libbutton" onclick="madLibs()">Create lib</button>
  <div id="mystory"></div>

<script src="js/main.js"></script>
</body>

JS:

function madLibs() {

  var mystory = document.getElementById("mystory");
  var thing = document.getElementById("thing").value;
  var title = document.getElementById("title").value;
  var adjective = document.getElementById("adjective").value;
  var noun = document.getElementById("noun").value;

  mystory.innerHTML = "Space: the final " + thing + ". " "These are the voyages of the starship " + title + ". Its five-year mission: to explore " + adjective + " new worlds, to seek out new life and new civilizations, to boldy go where no " + noun + " has gone before.";
}

2 个答案:

答案 0 :(得分:0)

你刚刚在mystory.innerHTML部分搞砸了一些引号。

function madLibs() {

  var mystory = document.getElementById("mystory");
  var thing = document.getElementById("thing").value;
  var title = document.getElementById("title").value;
  var adjective = document.getElementById("adjective").value;
  var noun = document.getElementById("noun").value;

  mystory.innerHTML = "Space: the final " + thing + ". These are the voyages of the starship " + title + ". Its five-year mission: to explore " + adjective + " new worlds, to seek out new life and new civilizations, to boldy go where no " + noun + " has gone before.";
}

Working codepen here.

答案 1 :(得分:0)

附近有一个双引号(&#34;):

function madLibs() {

var story = document.getElementById('story').getElementsByTagName('input');
var myobj = {};
for(var i=0; i<story.length; i++){
    myobj[story[i].id] = story[i].value;
}
// add innerHTML
document.getElementById('mystory').innerHTML = "Space: the final " + myobj.thing + ". These are the voyages of the starship " + myobj.title + ". Its five-year mission: to explore " + myobj.adjective + " new worlds, to seek out new life and new civilizations, to boldy go where no " + myobj.noun + " has gone before.";

}