JavaScript无线电输入
我正在做一项作业,我必须制作一个测验应用程序。我一次显示一个问题。用户必须从一组无线电输入中选择4个答案中的一个 由于某些原因,它只在用户选择第一个无线电输入时起作用,而其他的则没有响应 这是我的密码:JavaScript无线电输入,javascript,jquery,Javascript,Jquery,我正在做一项作业,我必须制作一个测验应用程序。我一次显示一个问题。用户必须从一组无线电输入中选择4个答案中的一个 由于某些原因,它只在用户选择第一个无线电输入时起作用,而其他的则没有响应 这是我的密码: var counter = 0; var questions = ["<h3>What is the 9 + 10 </h3>\n\ <input type='radio' name = 'radio' class='rad'
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的单选按钮,而不是其他单选按钮。你可能想要
替换document.querySelector.rad.addEventListenerchange,nextQuestion;按document.getElementByIdquestion.addEventListenerchange,nextQuestion
这是因为问题元素发生了更改事件。添加document.querySelector'.rad'.addEventListenerchange,nextQuestion;进入函数。所以,这是一种递归调用,并设置了一个条件
var计数器=0;
var questions=[什么是9+10\n\
19\n\
23\n\
66\n\
123 ,
什么是5+10\n\
15\n\
23\n\
44\n\
12 ,
什么是12+10\n\
25\n\
23\n\
64\n\
22 ,
什么是52+10\n\
25\n\
23\n\
64\n\
62
];
下一个问题;
函数nextQuestion{
ifquestions.length!=计数器{
控制台.日志计数器;
document.getElementByIdquestion.innerHTML=问题[计数器];
document.querySelector'.rad'.addEventListenerchange,nextQuestion;
计数器++;
}
}
我一次显示一个问题,它有4个无线电输入作为答案,要继续下一个问题,我必须选择其中一个输入,在我的情况下,只有第一个输入允许我继续,其他什么都不做。document.querySelector'.rad'仍然只指单个元素。我不这么认为。运行代码段,它工作正常。给出了完整的运行代码。我不喜欢你的答案。查看并否决投票。您是否尝试运行自己的代码片段?当你在第一个问题上按“23”、“66”或“123”时,什么都没有发生。只有“19”起作用,这是OP最初的问题。诚然,您的代码现在适用于每个问题的第一个选项,但它仍然只是第一个选项。这就是我在写“仍然只会引用单个元素”时的意思。你有没有把它解释成别的东西?