温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.linkedin.com/pulse/how-create-quiz-javascript-html-css-json-javascript-code-vzyge
点击访问原文链接

How to Create a Quiz with JavaScript (HTML + CSS + JSON)

How to Create a Quiz with JavaScript (HTML + CSS + JSON)

同意并加入领英

点击“继续加入或登录”,即表示您同意遵守领英的《用户协议》《隐私政策》《Cookie 政策》

登录查看更多内容 邮箱或手机 密码 显示 忘记密码 登录 使用邮箱登录 跳到主要内容 领英 马上加入 登录
How to Create a Quiz with JavaScript (HTML + CSS + JSON) 举报此文章 关闭菜单 JavaScript Developer WorldWide JavaScript Developer WorldWide Join the JavaScript Developers worldwide… 发布日期: 2026年2月28日 + 关注

This tutorial shows you how to build a simple quiz app using modern JavaScript. The quiz loads questions from a JSON file, lets users pick answers, tracks progress, and displays a final score.

https://basescripts.com/javascript-quiz-project-how-to-create-a-quiz-with-javascript-html-css-json

What you will build

Loads questions from questions.json Displays one question at a time Highlights the selected answer Next/Previous navigation Progress bar and answered count Final score screen

Project structure
quiz-project/
index.html
styles.css
app.js
questions.json
images/
q1.jpg
q2.jpg
q3.jpg 

Below is a modernized quiz project with:

✅ Real JSON file (no more json.js global variable) ✅ Clean HTML + CSS (simple) ✅ Modern JavaScript (ES modules) with fetch() ✅ Better structure: state, rendering, scoring, progress

1) questions.json (updated JSON)

Create a file named questions.json in the same folder as your HTML:

{
"title": "JavaScript Quiz",
"questions": [
{
"id": 1,
"question": "Which keyword declares a block-scoped variable?",
"image": "images/q1.jpg",
"choices": ["var", "let", "function", "const"],
"correctIndex": 1
},
{
"id": 2,
"question": "What does DOM stand for?",
"image": "images/q2.jpg",
"choices": ["Data Object Model", "Document Object Model", "Digital Order Map", "Document Order Map"],
"correctIndex": 1
},
{
"id": 3,
"question": "Which method selects the first matching element?",
"image": "images/q3.jpg",
"choices": ["querySelector()", "querySelectorAll()", "getElementsByClassName()", "getElement()"],
"correctIndex": 0
}
]
} 
2) index.html (modern HTML)




JavaScript Quiz






Quiz

Loading… Previous Next Submit

3) styles.css (simple styling)
body {
font-family: Arial, sans-serif;
background: #f5f5f5;
margin: 0;
padding: 20px;
color: #222;
}

.wrap {
max-width: 760px;
margin: 0 auto;
}

.header {
margin-bottom: 14px;
}

h1 {
margin: 0 0 6px;
}

.meta {
margin: 0;
color: #666;
font-size: 14px;
}

.card {
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
padding: 18px;
}

.question {
margin: 0 0 12px;
}

.image {
width: 100%;
max-height: 260px;
object-fit: cover;
border-radius: 6px;
border: 1px solid #eee;
display: none;
margin-bottom: 12px;
}

.choices {
display: grid;
gap: 10px;
margin: 12px 0 14px;
}

.choice {
border: 1px solid #ccc;
background: #f0f0f0;
padding: 10px;
border-radius: 6px;
cursor: pointer;
text-align: left;
}

.choice.selected {
background: #d8ebff;
border-color: #2b7de9;
}

.controls {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 12px;
}

.btn {
padding: 8px 14px;
border-radius: 6px;
border: 1px solid #bbb;
background: #eee;
cursor: pointer;
}

.btn.primary {
background: #2b7de9;
border-color: #2b7de9;
color: #fff;
}

.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}

.progress {
height: 10px;
background: #e3e3e3;
border-radius: 99px;
overflow: hidden;
}

.bar {
height: 10px;
width: 0%;
background: #2b7de9;
transition: width 0.2s ease;
} 
4) app.js (modern JavaScript)
const quizTitleEl = document.getElementById("quizTitle");
const quizMetaEl = document.getElementById("quizMeta");

const questionTextEl = document.getElementById("questionText");
const questionImageEl = document.getElementById("questionImage");
const choicesEl = document.getElementById("choices");

const prevBtn = document.getElementById("prevBtn");
const nextBtn = document.getElementById("nextBtn");
const submitBtn = document.getElementById("submitBtn");

const progressBarEl = document.getElementById("progressBar");
const progressTextEl = document.getElementById("progressText");

let quiz = null;
let currentIndex = 0;
let selected = []; // stores selected choice index per question (number or null)

init();

async function init() {
try {
const res = await fetch("./questions.json", { cache: "no-store" });
if (!res.ok) throw new Error("Could not load questions.json");
quiz = await res.json();

selected = new Array(quiz.questions.length).fill(null);

hookEvents();
render();
} catch (err) {
questionTextEl.textContent = "Error loading quiz data.";
progressTextEl.textContent = String(err.message || err);
}
}

function hookEvents() {
prevBtn.addEventListener("click", () => {
if (currentIndex > 0) {
currentIndex--;
render();
}
});

nextBtn.addEventListener("click", () => {
if (selected[currentIndex] === null) {
alert("Please choose an answer first.");
return;
}
if (currentIndex {
if (selected[currentIndex] === null) {
alert("Please answer the last question.");
return;
}
showResults();
});

// Optional keyboard shortcuts (1-4)
document.addEventListener("keydown", (e) => {
const n = Number(e.key);
if (n >= 1 && n {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "choice" + (selected[currentIndex] === idx ? " selected" : "");
btn.textContent = text;
btn.addEventListener("click", () => choose(idx));
choicesEl.appendChild(btn);
});

// controls
prevBtn.disabled = currentIndex === 0;

const onLast = currentIndex === total - 1;
nextBtn.style.display = onLast ? "none" : "inline-block";
submitBtn.style.display = onLast ? "inline-block" : "none";
submitBtn.disabled = selected[currentIndex] === null;

updateProgress();
}

function choose(choiceIndex) {
selected[currentIndex] = choiceIndex;
render();
}

function updateProgress() {
const total = quiz.questions.length;
const answered = selected.filter(v => v !== null).length;
const percent = Math.round((answered / total) * 100);

progressBarEl.style.width = percent + "%";
progressTextEl.textContent = `${answered}/${total} answered (${percent}%)`;
}

function showResults() {
const total = quiz.questions.length;

let score = 0;
quiz.questions.forEach((q, i) => {
if (selected[i] === q.correctIndex) score++;
});

const resultsHtml = `
Quiz Complete

You scored ${score} out of ${total}.

${quiz.questions.map((q, i) => { const isCorrect = selected[i] === q.correctIndex; return ` ${isCorrect ? "✅" : "❌"} Question ${i + 1} `; }).join("")} Restart `; document.getElementById("app").innerHTML = resultsHtml; document.getElementById("restartBtn").addEventListener("click", () => location.reload()); }
Important note (so fetch() works)

If you double-click index.html, some browsers block fetch() for local files.

Run a quick local server instead:

VS Code → Live Server or terminal (in the project folder):

python3 -m http.server 5500 

Then open: http://localhost:5500



JavaScript Code Examples Learn JavaScript Code Examples Learn 6,255 位关注者 订阅 3 1 条评论 赞 祝贺 支持 比心 有见地 有趣 评论 复制 LinkedIn Facebook X 关闭菜单 分享 Dr. James Naipao 2 个月 举报此评论 关闭菜单

I can cut and paste here

回复 1 次回应

要查看或添加评论,请登录

更多精彩文章 无上一项内容 Writing JavaScript That’s Easy to Delete Issue #25 2026年4月7日 Technical Debt in JavaScript Deep Dive 24 2026年4月4日 Build a JavaScript Slot Machine Game with localStorage and a Jackpot Counter 2026年3月17日 Thinking Together: Collaboration, Pair Programming & AI as a Team Member Vibe Coding — Issue #23 2026年3月15日 How Senior Engineers Evaluate Code Issue #23 2026年3月15日 Observability, Logging & Monitoring in JavaScript Systems 2026年3月11日 JavaScript Architecture Patterns for Large Applications Issue #8 2026年3月3日 Closures, Scope & Memory: What Really Happens Under the Hood Issue #7 2026年3月3日 JavaScript Flashcard Study App (JSON + Progress + Save Progress) 2026年2月28日 Designing JavaScript APIs That Are Hard to Misuse JavaScript Deep Dive 14 2026年1月30日 无下一项内容 浏览内容分类 Career Productivity Finance Soft Skills & Emotional Intelligence Project Management Education Technology Leadership Ecommerce User Experience Recruitment & HR Customer Experience Real Estate Marketing Sales Retail & Merchandising Science Supply Chain Management Future Of Work Consulting Writing Economics Artificial Intelligence Employee Experience Workplace Trends Fundraising Networking Corporate Social Responsibility Negotiation Communication Engineering Hospitality & Tourism Business Strategy Change Management Organizational Culture Design Innovation Event Planning Training & Development 展开 收起 领英 © 2026 关于 无障碍模式 用户协议 隐私政策 Cookie 政策 版权政策 品牌政策 访客设置 社区准则 العربية (阿拉伯语) বাংলা (孟加拉语) Čeština (捷克语) Dansk (丹麦语) Deutsch (德语) Ελληνικά (希腊语) English (英语) Español (西班牙语) فارسی (波斯语) Suomi (芬兰语) Français (法语) हिंदी (印地语) Magyar (匈牙利语) Bahasa Indonesia (印尼语) Italiano (意大利语) עברית (希伯来语) 日本語 (日语) 한국어 (韩语) मराठी (马拉地语) Bahasa Malaysia (马来语) Nederlands (荷兰语) Norsk (挪威语) ਪੰਜਾਬੀ (旁遮普语) Polski (波兰语) Português (葡萄牙语) Română (罗马尼亚语) Русский (俄语) Svenska (瑞典语) తెలుగు (泰卢固语) ภาษาไทย (泰语) Tagalog (他加禄语) Türkçe (土耳其语) Українська (乌克兰语) Tiếng Việt (越南语) 简体中文 (简体中文) 正體中文 (繁体中文) 关闭菜单 语言

How to Create a Quiz with JavaScript (HTML + CSS + JSON),AI智能索引,全网链接索引,智能导航,网页索引

    This tutorial shows you how to build a simple quiz app using modern JavaScript. The quiz loads questions from a JSON file, lets users pick answers, tracks progress, and displays a final score.