gpt4 book ai didi

javascript - 无法获取页面上单选按钮的值或索引。 [Javascript]

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:41 27 4
gpt4 key购买 nike

我正在开发一个测验应用程序,但我似乎无法获取页面上单选按钮的值或索引。

这是我的代码:

HTML:

<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input id="next" type="button" value="Next">
<input id="back" type="button" value ="Back">
<div id="results"></div>
</div>

JavaScript:

var allQuestions = [
{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},

{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},

{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},

{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}
];

var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.getElementById('next');
var backButton = document.getElementById('back');
var score = 0;
var questionIndex = 0;

// A function to show the question.

function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;

choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;

for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}

function checkScore() {
//var correctAnswers = allQuestions[questionIndex].correctAnswer;

var radios = document.querySelectorAll('[type=radio]');
var userAnswers;

for (var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
userAnswers = radios[i].value;
console.log(userAnswers);
}
}
}

showQuiz();

nextButton.addEventListener('click', function(){
questionIndex++;
showQuiz();
checkScore();
});

backButton.addEventListener('click', function(){
questionIndex--;
showQuiz();
});

首先,我认为这是因为我在 DOM 准备好之前调用了 checkAnswers() 函数,但事实并非如此,所以我被卡住了。

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

你的逻辑有问题。

当您在最后一个问题后单击“下一步”时,allQuestions[questionIndex] 未定义。如果还有问题,您需要检查一下。

而且我认为您的单选按钮选择器是错误的。看这个: javascript check radio buttons automatically

你需要类似的东西

radios = document.getElementsByTagName('INPUT');
for (var i = 0; i < radios.length; i++) {
if(radios[i].type == "radio"){
if(radios[i].checked) {
userAnswers = radios[i].value;
}
}
}

或者你只选择选中的元素

checkedbutton = document.querySelector("input[name='choice']:checked");

进一步:您应该将答案添加为按钮的“值”,例如

<input type="radio" name="choice" value="Ontario">

这样你就可以轻松获得值(value)

checkedbutton.value;

关于javascript - 无法获取页面上单选按钮的值或索引。 [Javascript],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892928/

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