我正在完成一项任务,我必须建立一个测验应用程序。我一次只显示一个问题。用户必须从一组无线电输入中选择4个答案中的一个。
由于某种原因,它仅在用户选择第一个无线电输入时有效,其他无法响应..
这是我的代码:
var counter = 0;
var questions = ["<h3>What is the 9 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='19'>19\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>66\n\
<input type='radio' name = 'radio' class='rad' value ='1'>123 ",
"<h3>What is the 5 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='15'>15\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>44\n\
<input type='radio' name = 'radio' class='rad' value ='1'>12 "
];
document.getElementById("question").innerHTML = questions[counter];
document.querySelector('.rad').addEventListener("change", nextQuestion);
function nextQuestion() {
console.log(counter);
counter++;
document.getElementById("question").innerHTML = questions[counter];
}
答案 0 :(得分:2)
document.querySelector('.rad')
仅指第一个单选按钮(一个说19
,而不是其他按钮)。您可能需要event delegation。
将document.querySelector('.rad').addEventListener("change", nextQuestion);
替换为document.getElementById("question").addEventListener("change", nextQuestion);
。
这适用于change
元素的question
事件bubbling up。
答案 1 :(得分:-1)
将document.querySelector('.rad').addEventListener("change", nextQuestion);
添加到该函数中。所以,它是一种递归的呼叫,并提出了突破的条件。
var counter = 0;
var questions = ["<h3>What is the 9 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='19'>19\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>66\n\
<input type='radio' name = 'radio' class='rad' value ='1'>123 ",
"<h3>What is the 5 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='15'>15\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>44\n\
<input type='radio' name = 'radio' class='rad' value ='1'>12 ",
"<h3>What is the 12 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='15'>25\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>64\n\
<input type='radio' name = 'radio' class='rad' value ='1'>22 ",
"<h3>What is the 52 + 10 </h3>\n\
<input type='radio' name = 'radio' class='rad' value ='15'>25\n\
<input type='radio' name = 'radio' class='rad' value ='23'> 23\n\
<input type='radio' name = 'radio' class='rad' value ='44'>64\n\
<input type='radio' name = 'radio' class='rad' value ='1'>62 "
];
nextQuestion();
function nextQuestion() {
if(questions.length != counter) {
console.log(counter);
document.getElementById("question").innerHTML = questions[counter];
document.querySelector('.rad').addEventListener("change", nextQuestion);
counter++;
}
}
&#13;
<div id="question"></div>
&#13;