将javascript函数中的变量值返回到html正文

时间:2015-10-01 05:41:16

标签: javascript html html5

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A Simple Quiz</title>
    <link rel="stylesheet" href="styles.css">
    <script>
      var q = ["How many days are in an year?", "How many days does february have in a leap year?","How many hours equals to 1 day?"];
      var a = [365, 29, 24];
      var fd =["Incorrect! Its 365", "Incorrect! It has 29 days", "Incorrect! It has 24 hours"];

      function scores() {
        document.getElementById('output').innerHTML = askquestion();
      }

      function askquestion() {
        var score=0;
          for(var i=0; i<3; i++) {
            var question=prompt(q[i]);
            if (question==a[i]){
              alert("Correct Answer");
              score=score +1;
            }
            else {
              alert(fd[i]);
            }
          }
        return score
      }
    </script>
  </head>

  <body>
    <h1> A Simple Quiz </h2>
    <hr>
    <script> scores()</script>
    <h2> The score is: </h2> <output id="finalscore"></output>
    <hr>
  </body>
</html>

以上是我的代码。我正在尝试打印“得分为:”旁边的分数。但我想不出办法!我知道我们不能使用print语句或任何东西。但我希望有一条出路。提前谢谢!

2 个答案:

答案 0 :(得分:2)

<强> HTML:

<div id="output"></div>

此外,在旁注中,您错误地将<h1>标记关闭为</h2>:)

您的JavaSript:

var q = ["How many days are in an year?", "How many days does february have in a leap year?","How many hours equals to 1 day?"];
var a = [365, 29, 24];
var fd =["Incorrect! Its 365", "Incorrect! It has 29 days", "Incorrect! It has 24 hours"];



function askquestion() {
  var score=0;
  for(var i=0; i<3; i++){
     var question=prompt(q[i]);
       if (question==a[i]){
        alert("Correct Answer");
        score=score +1;

       }
      else{
        alert(fd[i]);
       }
  }
document.getElementById('output').innerHTML = "Score is "+score; // On completion of the loop, you can append the result to your string this way.
}

askquestion();

小提琴: http://jsfiddle.net/hogfcjmc/

修改

你犯了两个简单的错误: -

<强> 1 即可。运行score()方法时,DOM中仍然不存在HTML。因此,设置为innerHTML的任何值都不起作用。

解决方案:将HTML <script>scores()</script>移到HTML代码之后。

.....
<h2> The score is: </h2> <output id="finalscore"></output>
<script> scores()</script>
....

<强> 2 即可。注意您使用了错误的Id名称output。它应该是finalscore

所以你的代码看起来像这样:

document.getElementById('finalscore').innerHTML = askquestion();

更新并正在使用小提琴:http://jsfiddle.net/xhs10xve/

答案 1 :(得分:0)

更改以下行

document.getElementById('output').innerHTML = askquestion();

document.getElementById('finalscore').innerHTML = askquestion();
相关问题