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

JS开发动态JSON题库测验如何获取答案在answerList的索引值

核心修改说明

  • 存储选项索引而非id:给每个checkbox新增自定义属性存储对应answerList的索引值,事件触发时直接读取该属性值即可
  • 每道题选中结果独立存储:声明全局对象按题目quid为键存储对应题目的选中索引数组,避免所有结果混到同一个数组里

修改后完整代码

//Parse JSON
let quizDyn = JSON.parse(`[
    {
        "quid":1,
        "question": "question 1",
        "answerList":["answer 1_1","answer 1_2"],
        "solution":[1],
        "type":"checkbox"

    }, {
        "quid":2,
        "question": "question 2",
        "answerList":["answer 2_1","answer 2_2","answer 2_3"],
        "solution":[0,1,2],
        "type":"checkbox"
    }, {
        "quid":3,
        "question": "question 3",
        "answerList":["answer 3_1","answer 3_2","answer 3_3","answer 3_4"],
        "solution":[0],
        "type":"checkbox"
    }
]`)

// 全局存储用户作答结果,键为题目quid,值为对应选中的索引数组
const userAnswers = {}

// just creating a div here
var spalteQuiz = document.createElement("div")
spalteQuiz.setAttribute("class", "spalteQuiz")
document.body.append(spalteQuiz)


for (var i = 0; i < quizDyn.length; i++) {

  var neuesQuiz = document.createElement("div")
  neuesQuiz.setAttribute("class", "quiz")
  var aktuellesQuiz = document.getElementById("pOut")

  neueFrage = document.createElement("p")
  neueFrage.setAttribute("class", "frage")
  neueFrage.setAttribute("id", "frage " + (i + 1) + " frage")
  neueFrage.setAttribute("name", "frage " + (i + 1) + " frage")
  neueFrage.textContent = quizDyn[i].question
  var aktuelleFrage = document.getElementById("divOut")

  spalteQuiz.append(neuesQuiz)
  neuesQuiz.append(neueFrage)

  var frageTyp = quizDyn[i].type
  var anzahlAntworten = quizDyn[i].answerList.length
  var quidi = quizDyn[i].quid
  var quid = quizDyn.quid
  var entferneLeerzeichen = str => str.replace(/[\s,.]/g, '')

  // 初始化当前题目的作答数组
  userAnswers[quidi] = []

  // function that's used for questions that are to be answered with checkboxes
  function istCheckbox() {

    //creating the <form>'s 
    var form = document.createElement("form")
    form.setAttribute("name", "frage" + quidi + "form")
    neuesQuiz.append(form)

    // creating the <input>'s
    for (let i = 0; i < anzahlAntworten; i++) {

      checkbox = document.createElement("input")
      checkbox.setAttribute("type", "checkbox")
      checkbox.setAttribute("name", "frage" + quidi + "checkbox")
      checkbox.setAttribute("id", entferneLeerzeichen(quizDyn[quidi - 1].answerList[i]))
      // 新增自定义属性存储选项索引和题目quid
      checkbox.dataset.index = i
      checkbox.dataset.quid = quidi


      // creating the <label>'s
      var label = document.createElement("label")
      label.textContent = quizDyn[quidi - 1].answerList[i]
      label.setAttribute("for", entferneLeerzeichen(quizDyn[quidi - 1].answerList[i]))

      // here i check if the checkbox is checked
      checkbox.addEventListener('change', function() {
        const currentIndex = Number(this.dataset.index)
        const currentQuid = Number(this.dataset.quid)
        const currentAnswerArr = userAnswers[currentQuid]
        // if it's checked, push the index to the array
        if (this.checked) {
          currentAnswerArr.push(currentIndex)
        } else {
          // when unchecking, find the index of the unchecked index
          index = currentAnswerArr.indexOf(currentIndex)
          // splice 1 object at the position of index
          if (index > -1) {
            currentAnswerArr.splice(index, 1)
          }
        }
        // 打印全局结果,可看到每道题的选中结果独立存储
        console.log(userAnswers)
      })

      // appending it all
      var zeilenUmbruch = document.createElement("br")
      form.append(checkbox)
      form.append(label)
      form.append(zeilenUmbruch)
    }
  }

  //there is more usually, because irelevant
  function istTyp() {
    istCheckbox()
  }

  istTyp()
}

效果说明

运行后全局对象userAnswers的结构如下,直接读取对应quid的数组和同下标的solution字段比对即可判断作答是否正确:

{
  1: [0,1], // 第一题选中索引0、1
  2: [0,1,2], // 第二题选中索引0、1、2
  3: [0] // 第三题选中索引0
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 11:27:04