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

如何将JavaScript数组值依次渲染到一系列div元素中实现试题选项展示

代码修复实现方案

现有代码核心问题

  • 语法错误:$('.Options').QuesPartA.forEach 写法错误,QuesPartA是独立定义的全局数组,不属于jQuery元素对象的属性,不能直接挂载调用
  • 匹配逻辑错误:直接使用$('.Options span')会选中页面所有题目下的全部选项span,无法做到每道题和对应选项一一匹配赋值
  • 取值逻辑错误:QuesPartA的每一项是包含option属性和answer属性的对象,不能直接拿元素对象当下标数组取值
  • 数量不匹配:写死循环生成30个题目容器,和QuesPartA的实际题目数量不一致,会出现大量空题目

修正后完整代码

const audioA = document.getElementById("AudioA");
const playBtn = document.getElementById("PlayBtn");

// 试题数组保持原有定义即可
let QuesPartA = [
  { 
    option: [
      "She doesn't have an appointment",
      "She must live somewhere else",
      "Her apartment isn't far away",
      "Her problem is complicated",
    ],
    answer: 2
  },
  { 
    option: [
      "There's no charge for phone calls",
      "She can call him later if she likes",
      "His phone is out of order too",
      "She can use his phone if she wants",
    ],
    answer: 1
  },
  { 
    option: [
      "It was simpler than he'd thought",
      "It was too hard to solve",
      "He couldn't find it",
      "He solved it even though it was hard",
    ],
    answer: 3
  }
];

function playPartA() {
  audioA.play();
  playBtn.style.color = "#777777";
  showQuestion();
}

function showQuestion(){
  // 动态按实际题目数量生成容器,不需要写死30
  for(let i = 0; i < QuesPartA.length; i++){
    $(".questionBox").append('<div class="Question"></div><div class="Options"><span></span><span></span><span></span><span></span></div>');
  } 
  $(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>'); 
  
  // 填充题号
  $('.Question').each(function(index){
    $(this).html("Number " + (index+1));
  }); 

  // 按索引匹配每道题和对应选项容器,单独填充内容
  QuesPartA.forEach((quesItem, index) => {
    const $currentOptBox = $('.Options').eq(index);
    const optList = quesItem.option;
    $currentOptBox.find('span').eq(0).text(optList[0]);
    $currentOptBox.find('span').eq(1).text(optList[1]);
    $currentOptBox.find('span').eq(2).text(optList[2]);
    $currentOptBox.find('span').eq(3).text(optList[3]);
    // 如需后续判分,可在此处给选项容器加自定义属性存储正确答案:$currentOptBox.attr('data-answer', quesItem.answer)
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:09:00