涉及知识点
介绍
页面显示一张卡片,上面有题目和选项,选择某个选项后点击提交,卡片内容换成其他题目。答完指定数目题目后会显示用户的答题结果,再次点击按钮可以重新答题。
代码
每次用户点击提交按钮时判断当次的答题结果,正确的话给标志位加一,然后销毁上一题的节点,渲染下一题的内容。
简单版本,只写了javascript,没有样式。
html:
<p class="question_title"></p>
<div class="answer_list"></div>
<button class="submit">提交</button>
javascript:
let res = [
{
title: '1+1=?',
answerList: ['10', '2', '3', '4','99'],
answer: '2'
}, {
title: '哪个是水果?',
answerList: ['西瓜', '小猫','小狗'],
answer: '西瓜'
}, {
title: '9-4=?',
answerList: ['3', '4', '5', '6'],
answer: '5'
}
]
let title = document.querySelector('.question_title')
let list = document.querySelector('.answer_list')
let submitBtn = document.querySelector('.submit')
let idx = 0
let correct = 0
showQuestion(idx)
submitBtn.addEventListener('click',()=>{
if(submitBtn.innerText=='重新答题'){
showQuestion(idx)
submitBtn.innerText = "提交"
return
}
let choose = document.querySelector('input:checked').value
if(choose == res[idx].answer){
correct++
console.log('success')
}
idx++
if(idx<res.length){
showQuestion(idx)
} else{
list.innerHTML = ""
title.innerText = `一共${
res.length}个问题,您答对了${
correct}个!`
submitBtn.innerText = "重新答题"
idx = 0
correct = 0
}
})
function showQuestion(num) {
list.innerHTML = ""
title.innerText = res[num].title
for (let i = 0; i < res[num].answerList.length; i++) {
let radio = document.createElement('input')
let text = document.createTextNode(res[num].answerList[i])
radio.type = 'radio'
radio.name = 'answer'
radio.value = res[num].answerList[i]
list.appendChild(radio)
list.appendChild(text)
}
}