
本文介绍一种无需修改 html 结构即可实现“每道题独立高亮所选答案”的 jquery 解决方案,通过精准作用域限定,避免跨题答案样式污染。
在开发多道选择题交互界面时,一个常见痛点是:当用户点击第 2 题的选项后,第 1 题已选中的答案高亮被意外清除——这是因为原始逻辑使用全局选择器 $(‘.__QNnChoiceContainer .__choicesMLExam.__theAnswerMLExam’) 移除了所有题目中带有 __theAnswerMLExam 类的选项,导致答案状态跨题耦合。
✅ 正确解法是:将操作范围严格限制在当前题目的上下文中。我们不再遍历所有 .__QNnChoiceContainer,而是从被点击的 元素出发,向上查找其所属的 .ChoicesExam 容器,再仅在此容器内执行「清除旧高亮 + 添加新高亮」操作。
以下是推荐的优化代码(兼容现有 html,零结构改动):
$('body').on('click', '.__choicesMLExam', function () { // 1. 找到当前选项所在的 ChoicesExam 容器(即本题的选择区) const $choiceContainer = $(this).closest('.ChoicesExam'); // 2. 清除该容器内所有已高亮的选项 $choiceContainer.find('.__choicesMLExam.__theAnswerMLExam').removeClass('__theAnswerMLExam'); // 3. 仅给当前点击项添加高亮类 $(this).addClass('__theAnswerMLExam'); });
? 关键点说明:
- 使用事件委托 $(‘body’).on(‘click’, …) 确保动态新增题目也能响应;
- $(this).closest(‘.ChoicesExam’) 精准定位当前题目的选择区域,天然隔离各题作用域;
- find(…) 和 removeClass() 仅影响本题内的选项,彻底杜绝跨题干扰;
- 无需为每个 .__QNnChoiceContainer 单独绑定事件,代码更简洁、性能更优。
? 额外建议:
- 若需支持「取消选择」(即再次点击已选项则取消高亮),可增加判断:
if ($(this).hasClass('__theAnswerMLExam')) { $(this).removeClass('__theAnswerMLExam'); } else { $choiceContainer.find('.__choicesMLExam.__theAnswerMLExam').removeClass('__theAnswerMLExam'); $(this).addClass('__theAnswerMLExam'); } - css 中的 :before 伪元素高亮方案保持不变,完全兼容。
该方案轻量、健壮、可扩展,适用于任意数量的选择题模块,是构建专业在线考试 ui 的推荐实践。