基于Bootstrap通过Data Attribute调用数组加载问答游戏题目
Hey there! Let's work through this quiz game challenge together. Based on what you've shared, here's a practical, step-by-step solution to get your category buttons loading the right questions into a Bootstrap modal dynamically:
First, update your category buttons to include a data-category attribute that maps directly to your question array names. This will let your JS know which dataset to pull from when a button is clicked.
<!-- Category Buttons --> <button type="button" class="btn btn-primary m-2" data-bs-toggle="modal" data-bs-target="#quizModal" data-category="history">历史类题目</button> <button type="button" class="btn btn-secondary m-2" data-bs-toggle="modal" data-bs-target="#quizModal" data-category="science">科学类题目</button> <!-- Bootstrap Modal --> <div class="modal fade" id="quizModal" tabindex="-1" aria-labelledby="quizModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="quizModalLabel">问答挑战</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="quizContent"> <!-- Dynamic question content loads here --> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" id="submitAnswer">提交答案</button> </div> </div> </div> </div>
Make sure each category array follows a consistent object format—this will make rendering questions way simpler. Here's an example:
// History category questions const historyArray = [ { question: "中国历史上第一个大一统王朝是哪个?", options: ["秦朝", "汉朝", "唐朝", "宋朝"], correctAnswer: "秦朝" }, { question: "文艺复兴起源于哪个欧洲国家?", options: ["意大利", "法国", "英国", "德国"], correctAnswer: "意大利" } ]; // Science category questions const scienceArray = [ { question: "水的化学分子式是?", options: ["H₂O", "CO₂", "O₂", "H₂"], correctAnswer: "H₂O" }, { question: "地球围绕哪个天体公转?", options: ["太阳", "月球", "火星", "木星"], correctAnswer: "太阳" } ];
Use Bootstrap's modal events (specifically show.bs.modal) to trigger loading questions when a button is clicked. This event fires right before the modal opens, so you can grab the category data and render content in time.
// Get modal element const quizModal = document.getElementById('quizModal'); // Listen for modal show event quizModal.addEventListener('show.bs.modal', function(event) { // Get the button that triggered the modal const triggerBtn = event.relatedTarget; // Pull the category from the button's data attribute const category = triggerBtn.getAttribute('data-category'); // Match category to the correct question array let selectedArray; switch(category) { case 'history': selectedArray = historyArray; break; case 'science': selectedArray = scienceArray; break; // Add more cases for additional categories default: alert('该分类暂无题目!'); return; } // Pick a random question (adjust this if you want sequential loading) const randomQuestionIndex = Math.floor(Math.random() * selectedArray.length); const activeQuestion = selectedArray[randomQuestionIndex]; // Render question and options into the modal body const quizContent = document.getElementById('quizContent'); quizContent.innerHTML = ` <div class="mb-4"> <p class="fs-5">${activeQuestion.question}</p> </div> <div class="options-list"> ${activeQuestion.options.map(option => ` <div class="form-check mb-3"> <input class="form-check-input" type="radio" name="quizOption" id="opt-${option}" value="${option}"> <label class="form-check-label" for="opt-${option}"> ${option} </label> </div> `).join('')} </div> `; // Store the correct answer in the modal's data attribute for later validation quizModal.setAttribute('data-correct-answer', activeQuestion.correctAnswer); }); // Handle answer submission document.getElementById('submitAnswer').addEventListener('click', function() { const selectedOption = document.querySelector('input[name="quizOption"]:checked'); const correctAnswer = quizModal.getAttribute('data-correct-answer'); if (!selectedOption) { alert('请先选择一个选项哦!'); return; } // Show result feedback if (selectedOption.value === correctAnswer) { alert('回答正确!🎉'); } else { alert(`答错啦,正确答案是:${correctAnswer}`); } // Close the modal after feedback const modalInstance = bootstrap.Modal.getInstance(quizModal); modalInstance.hide(); });
- Data attribute misalignment: Double-check that your
data-categoryvalue exactly matches your array variable name (case-sensitive!). - Bootstrap JS not loaded: Make sure you've included Bootstrap's JavaScript (and Popper.js, required for Bootstrap 5) in your project—load them in the order: Popper first, then Bootstrap JS.
- Rendering glitches: When using
map()to generate options, always use.join('')to convert the array of HTML strings into a single string (otherwise you'll get random commas in your UI).
内容的提问来源于stack exchange,提问作者Murphy1976

