带有单选按钮的数组键



我正在尝试使用每个单选按钮访问我的随机数组键 我只想将单选按钮放在阵列上 的allQuestions[index].anwsers键,它有 3 个索引键。

到目前为止,我无法做到,这是我的工作。

const allQuestions = [{
question: "Which of them is from compton",
anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
correctAnswer: "Kendrick"
},
{
question: "founder of HipHop",
anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
correctAnswer: "Bambata"
},
{
question: "Who won BET Hip Hop Album 2018",
anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
correctAnswer: "Kendrick",
},
{
question: "Best Female HipHop Art 2018",
anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
correctAnswer: "Nicki"
}
]
function render() {
var index, unique;
var print = '<ul>';
for (i = 0; i < allQuestions.length; i++) {
index = Math.floor(Math.random() * allQuestions.length);
}
var showQuiz = document.getElementById('showQuiz');
var showAnswers = document.getElementById('showAnswers');
showQuiz.style.color = 'red';
showQuiz.innerHTML = allQuestions[index].question;
showAnswers.innerHTML = allQuestions[index].anwsers;
// I'm tryin to ue sthe unshift method here but it' not workin
showAnswers.unshift('<input type="radio" value="allQuestions.anwsers[]');
}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>

看起来我们正在尝试在 DOM 元素上使用 Array 函数unshift()。我相信您要做的是为allQuestions.answers[]中的每个答案创建一个单选按钮列表,这可以通过 for 循环或这样的地图来完成:

编辑以添加answersAsHtmljoin(" ")这提高了可读性,并使用空格而不是默认逗号连接每个数组元素。

const allQuestions = [{
question: "Which of them is from compton",
anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
correctAnswer: "Kendrick"
},
{
question: "founder of HipHop",
anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
correctAnswer: "Bambata"
},
{
question: "Who won BET Hip Hop Album 2018",
anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
correctAnswer: "Kendrick",
},
{
question: "Best Female HipHop Art 2018",
anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
correctAnswer: "Nicki"
}
]
function render() {
var index, unique;
var print = '<ul>';
for (i = 0; i < allQuestions.length; i++) {
index = Math.floor(Math.random() * allQuestions.length);
}
var showQuiz = document.getElementById('showQuiz');
var showAnswers = document.getElementById('showAnswers');
var answersAsHtml = allQuestions[index].anwsers.map(ans => `<input type="radio" value="${ans}">${ans}</input>`).join(" ");
showQuiz.style.color = 'red';
showQuiz.innerHTML = allQuestions[index].question;
showAnswers.innerHTML = answersAsHtml;
}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>

您正在尝试写入 html 元素,这不是数组。您可能正在寻找更多类似的东西。

showAnswers.innerHTML = allQuestions[index].anwsers.map(function (answer){
return '<input type="radio" name="answers" value="' + answer + '"/>' + answer
})

最新更新