我正在完成一项任务,我必须建立一个测验应用程序。我一次只显示一个问题。用户必须从一组无线电输入中选择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];
}
document.querySelector('.rad')
只是指第一个单选按钮(一个说19
,而不是其他)。你可能想要event delegation。
用document.querySelector('.rad').addEventListener("change", nextQuestion);
替换document.getElementById("question").addEventListener("change", nextQuestion);
。
这是因为change
事件bubbling up到question
元素。
将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++;
}
}
<div id="question"></div>