简体   繁体   English

检查收音机输入时,我的 if 语句不起作用

[英]my if statement doesn't work when checking radio input

Im trying to validate radio input to check if its correct answer.我正在尝试验证无线电输入以检查其答案是否正确。
But it skips the line if (answer == allQuestions[q].correctAnswer)if (answer == allQuestions[q].correctAnswer)它会跳过这一行

here is whole code https://jsfiddle.net/alcatel/sopfmevh/1/这是整个代码https://jsfiddle.net/alcatel/sopfmevh/1/

for (let k = 0; k < answers.length; k++) {
  if (answers[k].checked) {
    answer = answers[k].value;
  }
}

// IT SKIPS THIS LINE !!
if (answer == allQuestions[q].correctAnswer) { // IT SKIPS THIS LINE!!
  alert("correct");
}

q++;
    
populate();

I think your If statement should look like this instead我认为你的 If 语句应该是这样的

if(answer == allQuestions[q].choices[allQuestions[q].correctAnswer]) {
        alert("correct");
    }

Editied this, just tried and works for me编辑了这个,刚刚尝试过,对我有用

You can also compare by using the index of the element in the array.您还可以使用数组中元素的索引进行比较。

if(allQuestions[q].choices.indexOf(answer) == allQuestions[q].correctAnswer) {
    alert("correct");
}

because I did it...因为我做到了...

 const allQuestions = [ { question : 'Where is Helsinki?' , choices : [ 'Sweden', 'Finland', 'Us' ] , correctAnswer: 1 } , { question : 'Where is Stockholm?' , choices : [ 'Norway', 'Iceland', 'Sweden' ] , correctAnswer: 2 } , { question : 'Where is Köpenhamn?' , choices : [ 'Denmark', 'Sweden', 'Norway' ] , correctAnswer: 0 } ] function* qList(arr) { for (let q of arr) yield q } const libQuestion = document.querySelector('h1') , formReplies = document.getElementById('list') , btNext = document.querySelector('button') , DomParser = new DOMParser() , qListRead = qList( allQuestions ) , score = { correct: 0, count:0 } ; var currentAnswer = '' ; function setNewQuestion() { formReplies.innerHTML = '' let newQuestion = qListRead.next() if (!newQuestion.done) { libQuestion.textContent = newQuestion.value.question currentAnswer = newQuestion.value.correctAnswer ++score.count newQuestion.value.choices.forEach((choice,indx)=> { let line = `<label><input type="radio" name="answer" value="${indx}">${ choice}</label>` , inLn = (DomParser.parseFromString( line, 'text/html')).body.firstChild ; formReplies.appendChild(inLn) }) } else { libQuestion.textContent = ` Score = ${score.correct} / ${score.count}` btNext.disabled = true } } setNewQuestion() btNext.onclick=()=> { if (formReplies.answer.value) { score.correct += ( currentAnswer == formReplies.answer.value ) setNewQuestion() } }
 <h1></h1> <p></p> <form id="list"></form> <br> <button>next</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM