You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML/JavaScript花生酱果冻测验:提交按钮无响应问题排查

Fixing Your Peanut Butter & Jelly Quiz Submit Button & Adding Feedback Features

Hey there! Let’s break down exactly how to fix that unresponsive submit button and implement the score tracking + answer feedback you want for your PB&J quiz.

First: Diagnose the Submit Button Issue

The most common reasons your submit button does nothing are:

  • No click event listener: You haven’t told the button what to do when clicked.
  • Default form submission: If your button is inside a <form> tag, it’s probably reloading the page instead of running your custom logic.
  • DOM not ready: Your JavaScript is running before the button exists on the page.

Quick Fix for the Button Response

Wrap your code in a DOMContentLoaded listener to ensure it runs after the page loads, and add a click handler with preventDefault() (if using a form):

document.addEventListener('DOMContentLoaded', () => {
  const submitBtn = document.getElementById('submit-btn');
  submitBtn.addEventListener('click', (e) => {
    e.preventDefault(); // Stop page reload if in a form
    // Your quiz logic goes here!
  });
});

Implementing Score Tracking & Answer Feedback

Let’s build out the core functionality for each question type with concrete code examples.

Step 1: Add HTML Structure with Correct Answer Markers

First, update your quiz HTML to include data attributes or hidden values for correct answers:

<div class="quiz">
  <!-- Single Choice Question -->
  <div class="question">
    <p>1. Which ingredient goes on top in a classic PB&J?</p>
    <div class="options">
      <label><input type="radio" name="q1" value="pb"> Peanut Butter</label>
      <label><input type="radio" name="q1" value="jelly" data-correct="true"> Jelly</label>
    </div>
  </div>

  <!-- Multiple Choice Question -->
  <div class="question">
    <p>2. Which are essential PB&J ingredients?</p>
    <div class="options">
      <label><input type="checkbox" name="q2" value="pb" data-correct="true"> Peanut Butter</label>
      <label><input type="checkbox" name="q2" value="jelly" data-correct="true"> Jelly</label>
      <label><input type="checkbox" name="q2" value="pickles"> Pickles</label>
    </div>
  </div>

  <!-- Short Answer Question -->
  <div class="question">
    <p>3. Describe a classic PB&J assembly order:</p>
    <input type="text" id="q3-input" placeholder="Your answer...">
    <input type="hidden" id="q3-correct" value="peanut butter first then jelly">
  </div>

  <button id="submit-btn">Submit Quiz</button>
  <div id="score-display"></div>
</div>

Step 2: Write the JavaScript Logic

Add this inside the click handler we set up earlier to process answers, track scores, and show feedback:

// Initialize score counters
let correct = 0;
let incorrect = 0;

// Clear old feedback first to avoid duplicates
document.querySelectorAll('.feedback').forEach(el => el.remove());

// 1. Process Single Choice Question
const q1Selected = document.querySelector('input[name="q1"]:checked');
if (q1Selected) {
  const feedback = document.createElement('span');
  feedback.className = 'feedback';
  if (q1Selected.dataset.correct === 'true') {
    feedback.textContent = ' ✅ Correct!';
    correct++;
  } else {
    feedback.textContent = ' ❌ Wrong!';
    incorrect++;
  }
  q1Selected.parentElement.appendChild(feedback);
}

// 2. Process Multiple Choice Question
const q2Selected = Array.from(document.querySelectorAll('input[name="q2"]:checked'));
const q2Correct = Array.from(document.querySelectorAll('input[name="q2"][data-correct="true"]'));
// Check if all correct options are selected and no extra ones
const q2IsCorrect = q2Selected.length === q2Correct.length && 
  q2Selected.every(opt => q2Correct.some(cOpt => opt.value === cOpt.value));

const q2Feedback = document.createElement('div');
q2Feedback.className = 'feedback';
q2Feedback.textContent = q2IsCorrect ? '✅ Correct!' : '❌ Wrong! Select all essential ingredients.';
q2IsCorrect ? correct++ : incorrect++;
document.querySelector('.question:nth-child(2) .options').appendChild(q2Feedback);

// 3. Process Short Answer Question
const q3Input = document.getElementById('q3-input');
const userAnswer = q3Input.value.trim().toLowerCase();
const correctAnswer = document.getElementById('q3-correct').value.toLowerCase();

const q3Feedback = document.createElement('span');
q3Feedback.className = 'feedback';
if (userAnswer.includes(correctAnswer)) { // Use strict equality for exact matches if needed
  q3Feedback.textContent = ' ✅ Correct!';
  correct++;
} else {
  q3Feedback.textContent = ' ❌ Wrong! Try mentioning the spread order.';
  incorrect++;
}
q3Input.parentElement.appendChild(q3Feedback);

// Display Final Score
document.getElementById('score-display').textContent = 
  `Score: ${correct} correct, ${incorrect} incorrect`;

Troubleshooting Tips

If it’s still not working:

  • Open your browser’s dev tools (F12) and check the Console tab for JavaScript errors (e.g., typos in element IDs, missing data attributes).
  • Verify that your button’s ID matches the one in your JS (submit-btn in our example).
  • Make sure you’re not accidentally reloading the page (double-check e.preventDefault() is included if using a form).

内容的提问来源于stack exchange,提问作者Progamminnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:12:27