一个简单的JavaScript疯狂的lib游戏

时间:2016-05-19 06:16:44

标签: javascript

我用JavaScript编写了一个简单的疯狂lib程序。所有的工作除了一件事。我的名字值显示未定义。代码如下。请帮我找出错误。

这是codepen链接。

HTML:

Name: <input type="text" id="name">
Favourite Color: <input type="text" name="color" id="color">
Fovourite Place: <input type="text" name="place" id="place">
Number: <input type="number" name="number" id="number">
<button id="launch">Launch</button>
<div id="story"></div>

Js:

var name = document.querySelector("#name");
var color = document.querySelector("#color");
var place = document.querySelector("#place");
var number = document.querySelector("#number");
var story = document.querySelector("#story")
var launch = document.querySelector("#launch");
launch.addEventListener("click", writeStory, false);

function writeStory(){
var launchedStory = "";
launchedStory += "<p>Welcome, " + name.value + ". ";
launchedStory += "Only silly people choose " + color.value + " as their favorite color.</p>";
launchedStory += "<p>Is " + place.value + " your current place or your birth place.</p>";
launchedStory += "<p>By the way, " + number.value + " is your serial number.</p>";

story.innerHTML = launchedStory;
}

4 个答案:

答案 0 :(得分:1)

您需要将变量名称从name更改为其他名称,因为解释器会将其解析为window.name

答案 1 :(得分:0)

在windows event onload函数中将代码写入script标记内。全局变量名称与window对象的name属性冲突。您还可以将全局变量的名称从名称更改为其他名称。

Sol 1。

var nameElement = document.querySelector("#name");

然后您可以使用nameElement.value

读取其值

但是不污染全局命名空间是件好事。所以在函数范围内编写代码。

Sol 2。

<script type="text/javascript">
  window.onload = function () {
    // your code here
  }
</script>

这是小提琴https://jsfiddle.net/mrk_m/L1an24ut/1/

答案 2 :(得分:0)

上面已经回答过,但是以更复杂的方式。简而言之,“名称”是一个JavaScript关键字,不应用作变量。我将“名称”的id更改为“ nombre”,并且效果很好。

https://codepen.io/SuperSchooler/pen/qeVqOj

HTML:

Name: <input type="text" id="nombre">
Favourite Color: <input type="text" name="color" id="color">
Favourite Place: <input type="text" name="place" id="place">
Number: <input type="number" name="number" id="number">
<button id="launch">Launch</button>
<div id="story"></div>

JS:

var name = document.querySelector("#nombre");
var color = document.querySelector("#color");
var place = document.querySelector("#place");
var number = document.querySelector("#number");
var story = document.querySelector("#story")
var launch = document.querySelector("#launch");
launch.addEventListener("click", writeStory, false);

function writeStory(){
    var launchedStory = "";
    launchedStory += "<p>Welcome, " + nombre.value + ". ";
    launchedStory += "Only silly people choose " + color.value + " as their favorite color.</p>";
    launchedStory += "<p>Is " + place.value + " your current place or your birth place.</p>";
    launchedStory += "<p>By the way, " + number.value + " is your serial number.</p>";

    story.innerHTML = launchedStory;
}

答案 3 :(得分:-1)

如果您正在执行madlibs,请执行以下操作:

puts "give me a transportation"
transportation = gets.chomp

然后,

puts "then we got in the {transportation} and went to Wendy's"