javascript - JS——价值指数;数组
问题描述
对某些人来说可能是一个简单的问题,但我目前被困在这里。
我要创建的是一个测验,它从 JSON 中获取问题、答案、解决方案和问题类型。
到目前为止,它有效,我得到了一个包含已选择答案的数组并删除了未选择的答案。但是数组中填充了 id,但我实际上想要它的 answerList 索引。
{
"quid":1,
"question": "question 1",
"answerList":["answer 1_1","answer 1_2"],
"solution":[1],
"type":"checkbox"
}
这就是我的 JSON 的样子。运行下面的代码并选中两个框时,我得到一个数组为 ["answer1_1", "answer1_2"]。但是我需要一个像 [0, 1] 这样的数组,因为我稍后想将它与解决方案进行比较,以查看选择是否正确。此外,由于有多个复选框问题(我删除了其他所有内容,因为它在这里无关紧要),它被全部推入同一个数组中。理想情况下,我会得到 arr1=[0, 1],如果在这种情况下两者都被选中,而下一个是 arr=[0, 1, 2]。
也许我已经坐在这里太久了,看不到我的问题的明显、简单的答案。
无论如何,这是一个代码片段。
//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"
}
]`)
// 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, '')
// variable used for my array
var loesung = []
// 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]))
// 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() {
// if it's checked, push the checkboxes id to the array
if (this.checked) {
loesung.push(this.id)
} else {
// when unchecking, find the index of the unchecked checkbox'S id
index = loesung.indexOf(this.id)
// splice 1 object at the position of index
loesung.splice(index, 1)
}
// console log the array
console.log(loesung)
})
// 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()
}
解决方案
根据您的设计,我评论了我对您的事件监听器所做的事情。
// Parse JSON
const 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"
}
]`)
// just creating a div here
const spalteQuiz = document.createElement('div')
spalteQuiz.setAttribute('class', 'spalteQuiz')
document.body.append(spalteQuiz)
for (let i = 0; i < quizDyn.length; i++) {
const neuesQuiz = document.createElement('div')
neuesQuiz.setAttribute('class', 'quiz')
const aktuellesQuiz = document.getElementById('pOut')
const 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
const aktuelleFrage = document.getElementById('divOut')
spalteQuiz.append(neuesQuiz)
neuesQuiz.append(neueFrage)
const frageTyp = quizDyn[i].type
const anzahlAntworten = quizDyn[i].answerList.length
const quidi = quizDyn[i].quid
const quid = quizDyn.quid
const entferneLeerzeichen = str => str.replace(/[\s,.]/g, '')
// variable used for my array
const loesung = []
// function that's used for questions that are to be answered with checkboxes
function istCheckbox () {
// creating the <form>'s
const form = document.createElement('form')
form.setAttribute('name', 'frage' + quidi + 'form')
neuesQuiz.append(form)
// creating the <input>'s
for (let i = 0; i < anzahlAntworten; i++) {
const checkbox = document.createElement('input')
checkbox.setAttribute('type', 'checkbox')
checkbox.setAttribute('name', 'frage' + quidi + 'checkbox')
checkbox.setAttribute(
'id',
entferneLeerzeichen(quizDyn[quidi - 1].answerList[i])
)
// creating the <label>'s
const 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 () {
// if it's checked, push the checkboxes id to the array
if (this.checked) {
// loesung.push(this.id)
// save this context for further use
const answerString = this.id
// re-add the space that was remove
// THIS VERY CRUDE, CONSIDER NOT USING SPACES AT ALL!(!!!)
const answerStringNew =
answerString.substr(0, 6) +
' ' +
answerString.substr(answerString.lastIndexOf('r') + 1)
// filter question array to get index of element which includes the choosen answer in the answerList
const quidElement = quizDyn.findIndex(el =>
el.answerList.includes(answerStringNew)
)
// get the index of the answer in answerList
const indexInAnswerList = quizDyn[quidElement].answerList.indexOf(answerStringNew)
// push index to loesung
loesung.push(indexInAnswerList)
} else {
// when unchecking, find the index of the unchecked checkbox'S id
const index = loesung.indexOf(this.id)
// splice 1 object at the position of index
loesung.splice(index, 1)
}
// console log the array
console.log(loesung)
})
// appending it all
const zeilenUmbruch = document.createElement('br')
form.append(checkbox)
form.append(label)
form.append(zeilenUmbruch)
}
}
// there is more usually, because irelevant
function istTyp () {
istCheckbox()
}
istTyp()
}
但是您也可以data
在创建元素时使用属性之类的东西来存储索引并使用它,而不是重建字符串。
// Parse JSON
const 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"
}
]`)
// just creating a div here
const spalteQuiz = document.createElement('div')
spalteQuiz.setAttribute('class', 'spalteQuiz')
document.body.append(spalteQuiz)
for (let i = 0; i < quizDyn.length; i++) {
const neuesQuiz = document.createElement('div')
neuesQuiz.setAttribute('class', 'quiz')
const aktuellesQuiz = document.getElementById('pOut')
const 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
const aktuelleFrage = document.getElementById('divOut')
spalteQuiz.append(neuesQuiz)
neuesQuiz.append(neueFrage)
const frageTyp = quizDyn[i].type
const anzahlAntworten = quizDyn[i].answerList.length
const quidi = quizDyn[i].quid
const quid = quizDyn.quid
const entferneLeerzeichen = str => str.replace(/[\s,.]/g, '')
// variable used for my array
const loesung = []
// function that's used for questions that are to be answered with checkboxes
function istCheckbox () {
// creating the <form>'s
const form = document.createElement('form')
form.setAttribute('name', 'frage' + quidi + 'form')
neuesQuiz.append(form)
// creating the <input>'s
for (let i = 0; i < anzahlAntworten; i++) {
const checkbox = document.createElement('input')
checkbox.setAttribute('type', 'checkbox')
checkbox.setAttribute('name', 'frage' + quidi + 'checkbox')
checkbox.setAttribute(
'id',
entferneLeerzeichen(quizDyn[quidi - 1].answerList[i])
)
// add an data attribut
checkbox.setAttribute('data-index', i)
// creating the <label>'s
const 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 () {
// if it's checked, push the checkboxes id to the array
if (this.checked) {
// loesung.push(this.id)
// push data-index to loesung
// this.dataset contains all attribuates 'data-'
// but dataset only hold strings, so Number()
// makes the index an integer again
loesung.push(Number(this.dataset.index))
} else {
// when unchecking, find the index of the unchecked checkbox'S id
const index = loesung.indexOf(this.id)
// splice 1 object at the position of index
loesung.splice(index, 1)
}
// console log the array
console.log(loesung)
})
// appending it all
const zeilenUmbruch = document.createElement('br')
form.append(checkbox)
form.append(label)
form.append(zeilenUmbruch)
}
}
// there is more usually, because irelevant
function istTyp () {
istCheckbox()
}
istTyp()
}
(我没有触及 uncheck 功能,因为您的问题围绕 answerList 数组的索引)
推荐阅读
- angular - 使用依赖的下拉菜单初始化 formGroup
- php - 如何将值从一个表单字段转移到 Laravel 中的另一个字段?
- google-chrome - 如何从 Outlook 加载项 (Office 365) 在 Chrome 浏览器中打开链接?
- javascript - 函数组件不支持 contextType
- java - 带有桌面应用程序的 Sqlite 数据
- javascript - 带有文件的表单-上传到 Json-字符串到 JavaBackend
- ansible - 将 module_defaults 属性应用于角色
- excel - VBA Range_Copy 宏 - 如何将相同的任务应用于后续行
- node.js - 免费 Heroku 计划和 TLS 证书
- python - 有没有办法选择一个字典,然后从那个字典中选择一个函数?