Javascript prompt命令在文档写入

时间:2016-12-16 17:14:23

标签: javascript

我的代码存在问题:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>The Ultimate Quiz Challenge</title>
 </head>
<body>
  <div class="container">
  <h1>The Ultimate Quiz Challenge</h1>
  <script>
  document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
  document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
  var question1 ="<p>What is the capital of England</p>";
  var firstanswer ="London";
  var question2 = "<p>How many sides are there to a square</p>";
  var secondanswer = 4;
  var noofquestions = 2;
  var count = 1
  /*var temp = eval('question' +1); */
  /*document.write(temp);*/
  /* main loop asking questions */
  while (count <= 2) {
      var temp = eval('question' + count);
      document.write(temp);
      var answer = prompt("Please type your answer "); 
      count++;
  }
  </script>
  </div>
</body>
</html>

当我将文件加载到浏览器(如chrome或safari)时,它无法按预期执行。

简而言之,在要求提供两个输入的提示窗口之前,document.write命令不会出现在屏幕上。我认为首先要看的是终极测验挑战,然后打开脚本标签中的命令一直到底部?

1 个答案:

答案 0 :(得分:0)

您应该在身体上使用onload事件,以便在呈现html页面后执行脚本。它应该与:

一起使用
<body onload="displayText()">

displayText()是您在脚本中定义的函数:

var displayText = function () {
  while (count <= 2) {
    var temp = eval('question' + count);
    document.write(temp);
    var answer = prompt("Please type your answer "); 
    count++;
  }
};

或类似的东西。