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

jQuery:事件委托中如何简化带有序列号的类选择器编写逻辑?

你只要做两处修改就能完全解决重复代码的问题:

第一步:修改题目生成逻辑,给选项增加公共类和数据属性

把原来生成选项的部分,给span新增统一的pilihan公共类,同时用data-question-id属性存储当前所属的题目序号,不需要再把序号作为类名的一部分作为区分逻辑的依据:

function showQuestion(){
    for(let i = 0; i < QuesPartA.length; i++){
        const questionNum = i + 1;
        $(".questionBox").append('<div class="Question">Number '+ questionNum +'</div>');
        $(".questionBox").append('<div class="Options" id="optId'+ questionNum +'">');
        QuesPartA[i]['option'].forEach(option => {
            // 这里修改span的属性,新增公共类和data属性
            $("#optId"+ questionNum).append('<span class="pilihan" data-question-id="'+ questionNum +'">'+option +' </span><br>');  
        });
        $(".questionBox").append('</div><br>'); // end Options div
    } 
    $(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>'); 
};

第二步:重写changeColor函数,只保留一个全局事件委托

直接通过公共类绑定点击事件,获取当前选项所属的题目序号后,只对同一题下的选项做背景色切换:

function changeColor(){
  $(".questionBox").on("click", ".pilihan", function() {
    // 获取当前选项所属的题目ID
    const questionId = $(this).data('question-id');
    // 把当前题目的所有选项背景重置为灰色
    $(`.pilihan[data-question-id="${questionId}"]`).css("background", "#ccc");
    // 把当前点击的选项设为红色
    $(this).css("background", "red");
  });
};

这种方案不管你有30道还是300道题,都只需要这几行代码就能实现全部题目的选项选中高亮效果,完全不需要重复写事件绑定逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:39:03