gpt4 book ai didi

JavaScript radio 输入

转载 作者:行者123 更新时间:2023-12-03 02:50:35 24 4
gpt4 key购买 nike

我正在做一项作业,我必须构建一个测验应用程序。我一次显示一个问题。用户必须从一组单选输入中选择 4 个答案之一。

由于某种原因,它仅在用户选择第一个 radio 输入时才有效,其他 radio 输入没有响应。

这是我的代码:

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 upquestion元素。

关于JavaScript radio 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com