无框架HTML模板制作使用及单题显示Quiz免复制实现方案问询
Hey Benjamin, great questions—let’s break these down one by one with practical, framework-free solutions that’ll save you from repetitive code.
You’ve got a few solid native options here, no external tools required:
Method 1: Native <template> Element (Recommended)
The <template> tag is purpose-built for this—it stores hidden, reusable HTML that doesn’t render by default. You can clone it and inject dynamic data whenever you need it.
<!-- Define your template --> <template id="blog-post-template"> <article class="blog-post"> <h2 class="post-title"></h2> <p class="post-date"></p> <div class="post-content"></div> </article> </template> <!-- Where we'll render the template --> <div id="blog-container"></div> <script> // Grab the template and target container const template = document.getElementById('blog-post-template'); const container = document.getElementById('blog-container'); // Sample post data const postData = { title: 'How to Use HTML Templates Without Frameworks', date: 'October 12, 2024', content: 'This post is rendered from a native HTML template—no React, Vue, or Angular needed!' }; // Clone the template's content (true = deep clone all child elements) const postClone = template.content.cloneNode(true); // Populate the template with data postClone.querySelector('.post-title').textContent = postData.title; postClone.querySelector('.post-date').textContent = postData.date; postClone.querySelector('.post-content').textContent = postData.content; // Add the finished post to the DOM container.appendChild(postClone); </script>
Method 2: JavaScript Template Literals
If you prefer keeping template logic in JS (or need to add dynamic conditionals), template literals (backticks `) work perfectly. They let you write HTML directly in strings and interpolate variables.
<div id="greeting-container"></div> <script> function renderGreeting(user) { // Use template literals to build HTML with dynamic data return ` <div class="greeting"> <h3>Hello, ${user.name}!</h3> <p>Your favorite color is ${user.favoriteColor}—nice choice.</p> </div> `; } // Pass in user data and render const currentUser = { name: 'Benjamin', favoriteColor: 'blue' }; document.getElementById('greeting-container').innerHTML = renderGreeting(currentUser); </script>
Absolutely—this is exactly the kind of problem templates were made for. You’ll define a single question structure once, then feed it an array of question data. No more duplicating HTML for every question!
Here’s a complete, working example:
<!-- Optional basic styling to make the quiz look clean --> <style> .quiz-wrapper { max-width: 600px; margin: 2rem auto; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .question-text { font-size: 1.2rem; margin-bottom: 1.5rem; } .option-btn { display: block; width: 100%; padding: 0.8rem; margin-bottom: 0.5rem; border: none; border-radius: 4px; background: #f5f5f5; text-align: left; cursor: pointer; transition: background 0.2s; } .option-btn:hover { background: #e5e5e5; } </style> <!-- Define the reusable question template --> <template id="quiz-question-template"> <div class="quiz-wrapper"> <h3 class="question-counter"></h3> <p class="question-text"></p> <div class="options-list"></div> </div> </template> <!-- Target container for the quiz --> <div id="quiz-root"></div> <script> // 1. All your quiz questions live here—easy to update/add new ones const quizData = [ { id: 1, question: 'Which of these is a valid HTML self-closing tag?', options: ['<div>', '<img>', '<p>', '<h1>'], correctAnswer: '<img>' }, { id: 2, question: 'What does CSS stand for?', options: ['Computer Style Sheets', 'Creative Style Sheets', 'Cascading Style Sheets', 'Colorful Style Sheets'], correctAnswer: 'Cascading Style Sheets' }, { id: 3, question: 'Which method adds an element to the end of an array in JavaScript?', options: ['shift()', 'unshift()', 'push()', 'pop()'], correctAnswer: 'push()' } ]; // 2. Setup variables and grab DOM elements const questionTemplate = document.getElementById('quiz-question-template'); const quizRoot = document.getElementById('quiz-root'); let currentQuestionIndex = 0; // 3. Function to render a single question from the template function renderCurrentQuestion() { const currentQuestion = quizData[currentQuestionIndex]; // Clone the template content const questionClone = questionTemplate.content.cloneNode(true); // Populate static question details questionClone.querySelector('.question-counter').textContent = `Question ${currentQuestion.id}/${quizData.length}`; questionClone.querySelector('.question-text').textContent = currentQuestion.question; // Generate option buttons dynamically const optionsContainer = questionClone.querySelector('.options-list'); currentQuestion.options.forEach(option => { const btn = document.createElement('button'); btn.className = 'option-btn'; btn.textContent = option; btn.addEventListener('click', () => handleAnswer(option, currentQuestion.correctAnswer)); optionsContainer.appendChild(btn); }); // Clear previous content and render the new question quizRoot.innerHTML = ''; quizRoot.appendChild(questionClone); } // 4. Handle answer selection and navigation function handleAnswer(selectedOption, correctAnswer) { if (selectedOption === correctAnswer) { alert('Nice job, that’s correct! 🎉'); } else { alert(`Oops, wrong answer. The correct choice is: ${correctAnswer}`); } // Move to next question or end the quiz currentQuestionIndex++; if (currentQuestionIndex < quizData.length) { renderCurrentQuestion(); } else { quizRoot.innerHTML = '<h2>You’ve completed the quiz! 🎊</h2>'; } } // 5. Start the quiz by rendering the first question renderCurrentQuestion(); </script>
Why this works so well:
- Zero copy-paste: The question HTML is written once in the
<template>—all questions inherit the same format automatically. - Easy maintenance: To add a new question, just add an object to the
quizDataarray—no need to touch the template or HTML structure. - Scalable: You can easily add features like score tracking, progress bars, or different question types (true/false, short answer) by updating the template and data structure.
内容的提问来源于stack exchange,提问作者Benjamin Sommer

