๐ป ์ฃผ์ : ํด์ฆ๋ฅผ ํผ ํ ๋ช ๊ฐ๋ฅผ ๋ง์ท๋์ง ๋ณด์ฌ์ค.
const quizData = [
{
question: "์น ๋ธ๋ผ์ฐ์ ์์ ์คํ๋๋ ์ธ์ด๋?",
a: "Java",
b: "C",
c: "Python",
d: "JavaScript",
correct: "d",
},
{
question: "CSS๋ ๋ฌด์์ ์๋ฏธํ๋?",
a: "Central Style Sheets",
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
},
{
question: "HTML๋ ๋ฌด์์ ์๋ฏธํ๋",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
},
{
question: "JavaScript๊ฐ ์ถ์๋ ์ฐ๋๋?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
},
];
// ํ์ฌ ํด์ฆ์ ์ธ๋ฑ์ค๋ฅผ ๋ํ๋ด๋ ๋ณ์
let currentQuiz = 0
// ์ฌ์ฉ์์ ์ ์
let score = 0
loadQuiz()
function loadQuiz() {
deselectAnswers()
const currentQuizData = quizData[currentQuiz]
questionEl.innerText = currentQuizData.question
a_text.innerText = currentQuizData.a
b_text.innerText = currentQuizData.b
c_text.innerText = currentQuizData.c
d_text.innerText = currentQuizData.d
}
function deselectAnswers() {
answerEls.forEach(answerEl => answerEl.checked = false)
}
function getSelected() {
let answer
answerEls.forEach(answerEl => {
if(answerEl.checked) {
answer = answerEl.id
}
})
return answer
}
deselectAnswers(): ๋ต์ ์ ํ ์ํ๋ฅผ ์ด๊ธฐํ
const currentQuizData = quizData[currentQuiz]
currentQuiz์ ํด๋นํ๋ ํด์ฆ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์จ๋ค.
innerText
๊ฐ questionEl๊ณผ a_text, b_text, c_text, d_text ์์์ ํด์ฆ ๋ฐ์ดํฐ์ ์ง๋ฌธ๊ณผ ๊ฐ ์ ํ์ง๋ฅผ ํ ๋นํ๋ค.
answerEls.forEach(answerEl => answerEl.checked = false)
answerEls ๋ฐฐ์ด์ ๋ชจ๋ ์์์ ์ ํ ์ํ๋ฅผ ํด์ ํ๋ค.
์ฌ์ฉ์๊ฐ ์ ํด์ฆ๋ก ๋์ด๊ฐ ๋ ์ด์ ํด์ฆ์ ์ ํ์ ์ด๊ธฐํํ๋ค.
function getSelected() { ... }:
์ ํ๋ ๋ต์ ๊ฐ์ ธ์จ๋ค. ์ ํ๋ ๋ต์์ id๋ฅผ ๋ฐํํ๋ค.
answerEls.forEach(answerEl => { ... })
answerEls ๋ฐฐ์ด์ ๊ฐ ์์์ ๋ํด ๋ฐ๋ณต๋ฌธ์ ์คํํ๋ค.
if(answerEl.checked) { ... }
ํ์ฌ ์์๊ฐ ์ ํ๋์ด ์๋์ง๋ฅผ ํ์ธํ๊ณ , ์ ํ๋์ด ์๋ค๋ฉด ํด๋น ์์์ id๋ฅผ answer ๋ณ์์ ํ ๋นํ๋ค.
submitBtn.addEventListener('click', () => {
const answer = getSelected()
if(answer) {
if(answer === quizData[currentQuiz].correct) {
score++
}
currentQuiz++
if(currentQuiz < quizData.length) {
loadQuiz()
} else {
quiz.innerHTML = `
<h2>๋น์ ์ ${score}/${quizData.length} ๋ฌธ์ ๋ฅผ ๋งํ์ต๋๋ค!</h2>
<button>๋ค์ํ๊ธฐ</button>
`
}
}
})
const answer = getSelected()
getSelected() ํจ์๋ฅผ ํธ์ถํ์ฌ ์ฌ์ฉ์๊ฐ ์ ํํ ๋ต์ ๊ฐ์ ธ์จ๋ค.
if(answer === quizData[currentQuiz].correct) { ... }
์ฌ์ฉ์๊ฐ ์ ํํ ๋ต answer์ ํ์ฌ ํด์ฆ์ ์ฌ๋ฐ๋ฅธ ๋ต quizData[currentQuiz].correct๋ฅผ ๋น๊ตํ๋ค.
๋ง์ฝ ๋ง์๋ค๋ฉด score๊ฐ ์ฆ๊ฐ๋๋ค.
currentQuiz++: ๋ค์ ํด์ฆ๋ก ๋์ด๊ฐ ์ ์๋๋ก currentQuiz๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
if(currentQuiz < quizData.length) { ... }
๋ง์ฝ ์์ง ๋ชจ๋ ํด์ฆ๋ฅผ ๋ค ํ์ง ์์๋ค๋ฉด, ๋ค์ ํด์ฆ๋ฅผ ๋ก๋ํ๊ธฐ ์ํด loadQuiz() ํจ์๋ฅผ ํธ์ถํ๋ค.
quiz.innerHTML = ...
quiz ์์์ ๋ด์ฉ์ ๋ณ๊ฒฝํ์ฌ ์ต์ข
์ ์์ "๋ค์ํ๊ธฐ" ๋ฒํผ์ ์ถ๋ ฅํ๋ค.
location.reload()
"๋ค์ํ๊ธฐ" ๋ฒํผ์ ํด๋ฆญํ๋ฉด ํ์ฌ ํ์ด์ง๋ฅผ ์๋ก๊ณ ์นจํ์ฌ ํด์ฆ๋ฅผ ๋ค์ ์์ํ ์ ์๋ค.