Step 4: The Finish Line چالش 4 از جلسهی 20، سخت
قدم آخر: پایانِ مسابقه و رنگها.
- وقتی جواب درست است رنگِ result را با style.color سبز (green) کن و وقتی غلط است قرمز (red).
- آخرِ تابع را عوض کن: بعد از i = i + 1; یک if بگذار. اگر i < questions.length بود سؤالِ بعدی را نشان بده.
- وگرنه (else) مسابقه تمام شده است: در تگِ question بنویس Finished! Your score: + امتیاز + out of + تعداد سؤالها با questions.length (مثلاً Finished! Your score: 2 out of 3) و div#buttons را با style.display = "none" قایم کن.
<style>
body {
text-align: center;
font-family: Arial;
}
#question {
font-size: 28px;
}
button {
font-size: 20px;
padding: 10px 30px;
}
</style>
<h1>Yes or No Quiz</h1>
<p id="question">A cat says meow.</p>
<div id="buttons">
<button onclick="answer('yes')">Yes</button>
<button onclick="answer('no')">No</button>
</div>
<p id="result"></p>
<p>Score: <span id="score">0</span></p>
<script>
let questions = ["A cat says meow.", "A spider has six legs.", "The sun is a star."];
let answers = ["yes", "no", "yes"];
let i = 0;
let score = 0;
function answer(choice) {
if (choice === answers[i]) {
score = score + 1;
document.getElementById("score").textContent = score;
document.getElementById("result").textContent = "Correct!";
} else {
document.getElementById("result").textContent = "Wrong!";
}
i = i + 1;
document.getElementById("question").textContent = questions[i];
}
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 20: پروژه: مسابقهی بله یا نه
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js