如何使用jQuery实现分区显隐、计分、带进度条的动态quiz问答
问题修复与功能实现方案
1. 区块显隐异常修复
你当前的问题是仅给正确页的下一步按钮写了跳转逻辑,错误页的按钮没有绑定对应跳转事件,且逐个控制每个区块的显隐逻辑太冗余容易遗漏。
优化方案
- 先给所有题目、对错反馈、结果页区块统一加公共类
quiz-block,初始化直接批量隐藏:
let currentQuestion = 1; // 全局存储当前题号 let correctCount = 0; // 全局存储答对题数 const TOTAL_QUESTION = 4; $(document).ready(function() { $(".quiz-block").hide(); // 显示首页或者第一题 $(".start-page, .question1").show(); });
- 给所有下一步按钮统一加公共类
next-btn,统一绑定跳转逻辑:
$('.next-btn').on('click', function() { // 隐藏当前题的反馈区块 $(`.question${currentQuestion}_correct, .question${currentQuestion}_incorrect`).hide(); currentQuestion++; // 所有题目答完跳结果页 if(currentQuestion > TOTAL_QUESTION) { const score = correctCount * 25; $('.result-page').show().html(`<p>答对题数:${correctCount}/${TOTAL_QUESTION}</p><p>总得分:${score}%</p>`); return; } // 显示下一题 $(`.question${currentQuestion}`).show(); // 更新进度条(后面进度条功能会用到) updateProgress(); })
- 每道题提交答案判断对错时,仅需要控制当前题的对错页显示即可:
// 以第一题提交逻辑为例 $('.question1 .submit-btn').on('click', function() { // 这里写你判断答案是否正确的逻辑 const isCorrect = 你的判断逻辑; if(isCorrect) { correctCount++; $('.question1_correct').show(); } else { $('.question1_incorrect').show(); } $('.question1').hide(); })
2. 自定义Checkbox样式修复
需要先隐藏原生input,同时给label绑定对应input的id才能触发选中状态:
CSS代码
/* 隐藏原生checkbox */ .question-item input[type="checkbox"] { position: absolute; opacity: 0; width: 0; height: 0; } /* 自定义选项基础样式 */ .question-item label { position: relative; padding-left: 32px; cursor: pointer; line-height: 24px; } /* 未选中状态的自定义框/图片 */ .question-item label::before { content: ''; position: absolute; left: 0; top: 0; width: 24px; height: 24px; border: 1px solid #ccc; border-radius: 4px; background: #fff; /* 替换成自定义图片就加 background: url(你的未选中图片地址) center/cover no-repeat; */ } /* 选中状态的勾选标记/图片 */ .question-item input[type="checkbox"]:checked + label::after { content: '✓'; position: absolute; left: 4px; top: -2px; font-size: 18px; color: #27ae60; font-weight: bold; /* 替换成自定义图片就加 content: ''; 然后设置background属性即可 */ }
HTML结构注意事项
每个input要设置唯一id,label的for属性和对应input的id保持一致,点击label才能触发选中:
<div class="question-item"> <input type="checkbox" id="q1-a"> <label for="q1-a">选项A</label> </div>
3. 得分统计功能实现
直接用前面定义的全局变量correctCount统计答对题数,单题25分,总得分就是correctCount * 25,结果页直接渲染对应数值即可,参考第一部分跳转结果页的代码。
4. 步骤进度条实现
先加公共进度条HTML
放在所有题目的公共头部位置:
<div class="progress-wrap"> <div class="progress-bar"></div> <p class="progress-tip">第1题/共4题</p> </div>
加进度条样式
.progress-wrap { margin-bottom: 20px; } .progress-bar { height: 8px; width: 25%; background: #3498db; border-radius: 4px; transition: width 0.3s ease; } .progress-tip { text-align: right; font-size: 14px; color: #666; margin: 6px 0 0; }
加进度条更新方法
function updateProgress() { const percent = (currentQuestion / TOTAL_QUESTION) * 100; $('.progress-bar').css('width', percent + '%'); $('.progress-tip').text(`第${currentQuestion}题/共${TOTAL_QUESTION}题`); }
切换题目时调用这个方法即可,参考第一部分切换题目的代码。
内容的提问来源于stack exchange,提问作者Jeff_dan13
相关产品推荐
相关产品推荐

