为什么JavaScript变量值不显示?

时间:2018-01-20 17:59:28

标签: javascript

我正在尝试练习JavaScript,我想在创建的元素中输出变量。但是不输出存储在变量中的值。只有单词回答。我控制台记录了变量,它有一个数字值。但它不显示我不知道为什么这个词?



var name, computer, age, answer;

name = window.prompt("What is your name?");
alert("you chose " + name);

computer = window.prompt("How old where you when you used a computer");
alert(computer + "  0.0");

age = window.prompt("How old are you now?");
alert("you are " + age);

if (age - computer < 0) {
  age = 0;
  computer = 0;
}

answer = age - computer;

var con = document.getElementById('container');
var h1 = document.createElement('h1');
var h1Text = document.createTextNode('answer');
h1.appendChild('h1Text');
con.appendChild('h1');

// document.write(age + " - " + computer + " = ");
// document.write(answer + "<br>");
&#13;
body {
  background-color: orange;
}

div {
  background-color: green;
  max-width: 960px;
  margin: 3em auto;
}
&#13;
<div id="container"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您正在将字符串answer而不是变量answer传递给createTextNode,因此正在显示答案文字,h1h1Text需要

中的变量
h1.appendChild(h1Text);
con.appendChild(h1);

工作代码段

var name, computer, age, answer;

name = window.prompt("What is your name?");
alert("you chose " + name);

computer = window.prompt("How old where you when you used a computer");
alert(computer + "  0.0");

age = window.prompt("How old are you now?");
alert("you are " + age);

if (age - computer < 0) {
  age = 0;
  computer = 0;
}

answer = age - computer;

var con = document.getElementById('container');
var h1 = document.createElement('h1');
var h1Text = document.createTextNode(answer);
h1.appendChild(h1Text);
con.appendChild(h1);

// document.write(age + " - " + computer + " = ");
// document.write(answer + "<br>");
body {
  background-color: orange;
}

div {
  background-color: green;
  max-width: 960px;
  margin: 3em auto;
}
<div id="container"></div>

答案 1 :(得分:-1)

这是因为你没有为任何事情分配变量答案。

尝试

h1Text.innerHTML = answer;