用JavaScript对自己进行测验

时间:2019-05-17 02:41:54

标签: javascript html

我有一个针对高中javascript课堂的实验室,应该使用数组作为对自己进行测验的一种方式。实验室按部就班地进行了工作,但是当我单击按钮时,我仍然没有让我的函数myQuiz()无法运行

我尝试将脚本标签最初放置在头部,但是当函数无法运行时,我将其放置在主体部分的末尾。但是单击该按钮后,该功能仍然无法运行。

以下是我的脚本标签中的内容:

function myQuiz() {
     var questions: ["What is Bryce's favorite color", "What is Bryce's favorite instrument(s) to play?", "When is Bryce's birthday?", "How tall is Bryce?", "Favorite band?"];
     var answers: ["Red", "Double Bass and Violin", "3/24", "6'4", "LOONA"];
     alert("Welcome to WHO IS BRYCE DAVIS?");
     for (var count = 0; count < questions.length; count++) {
         var guess = prompt(questions[count]);
         if (guess == answers[count]) {
            alert('Correct');
         } else {
            alert('WRONG!');
         }
     }
     alert("Thanks for playing!");
}

我希望有一个测验,允许用户回答问题或对错。

1 个答案:

答案 0 :(得分:0)

如果使用多个窗体控件(例如<input><textarea>等),则将所有内容包装在<form>标记中。这样做使我们可以使用HTMLFormElementHTMLFormControlsCollection API,这使我们可以轻松访问<form>和表单控件。

看来答案必须由用户输入-这要求在anser数组和输入内容之间完全匹配的文本-不好。在演示中,动态添加了<input><output>标签,并且在提交<form>时,每个<input>的值都与答案数组匹配。使用.includes()方法,因此只需要用户的答案包括文本即可正确回答问题。 (例如,“ A”和“ AB”都是正确的,因为它们都包含“ A”)。演示中将评论详细信息。

const Q = ['What... is your name?', 'What... is your quest?', 'What... is the air-speed velocity of an unladen swallow?'];
const A = ['bryce', 'holy grail', '11'];

// Reference <ol>
const list = document.querySelector('ol');
// Reference <form>
const quiz = document.forms.quiz;

/* 
-for each iteration...
-Add a htmlString (.innerHTML +=) to <ol> (list)...
-Interpolate the question from Q array that corresponds to
 the current index (${Q[i]})
 */
for (let i = 0; i < Q.length; i++) {
  list.innerHTML += `
  <li>${Q[i]}<br>
    <input name='answer' type='text'>
    <output></output> 
  </li>
  `;
}

// Register <form> to submit event -- call QA()
quiz.onsubmit = QA;

/*
-Pass the Event Object
A-Prevent the data of <form> being sent to a server
B-Collect all form controls with the [name='answer'] into
 an array
-for each iteration...
C-Get the value of the <input name='answer'> in the
  position of current index 
D-if the value of the <input> .includes() the string in 
  A array at the corresponding index...
E-Get the <output> that follows the <input> and set it's
  value to 'Correct!'...
F-Otherwise set it's value to "Wrong"
*/
function QA(e) {
  e.preventDefault(); //A
  const answers = Array.from(this.elements.answer);//B  
  for (let i = 0; i < A.length; i++) {
    let answer = answers[i].value.toLowerCase();//C
    if (answer.includes(A[i])) {//D
      answers[i].nextElementSibling.value = 'Correct!';//E
    } else {
      answers[i].nextElementSibling.value = 'Wrong';//F
    }
  }
  return false;
}
<form id='quiz'>
  <ol></ol>
  <button type='submit'>Done</button>
</form>