javascript - 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)
here is whole code 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();
解决方案
因为我做到了...
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>
推荐阅读
- angular - 上传到 go daddy 的 Angular Web 应用程序显示空白页面
- azure-devops - 如何使用 Azure DevOps Server 在管道上使用 vmImage?
- python-3.x - 无法单击 Selenium 中的按钮
- google-chrome-devtools - 为什么 Chrome 85 Devtools 中缺少体验行?
- javascript - 正则表达式验证没有特殊字符的 URL/URI
- javascript - 使用 vue-test-utils 和 Jest 测试方法的内部逻辑
- c# - 如何通过 ref 将参数传递给成员变量?
- javascript - 每分钟在不同位置重新定位视频上的水印,无需插件
- python - 使用 selenium 查找空输入框
- graphql - 为什么多个媒体字段返回相同的图像?