javascript - 带有单选按钮的数组键
问题描述
我正在尝试使用每个单选按钮访问我的随机数组键我只想将单选按钮放置在键的数组上,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>
解决方案
您正在尝试写入一个 html 元素,这不是一个数组。您可能正在寻找更像这样的东西。
showAnswers.innerHTML = allQuestions[index].anwsers.map(function (answer){
return '<input type="radio" name="answers" value="' + answer + '"/>' + answer
})
推荐阅读
- python - Matplotlib 视图限制最小值小于 1,具有 2 个不同的比例图
- java - 邮寄图像视图而不将其保存在java中
- c# - VS 2019 中 Windows 安装程序的替代解决方案是什么?
- c# - 在同一台计算机上安装开发和生产版本
- reactjs - Redux 表单“更改”被调用两次
- r - R- 段落内的词共现频率
- c# - 当我希望我的玩家跳跃时,他正在飞行(Unity2d)
- installshield - InstallShield - 功能组只选择一个
- python - 为回测和机器学习指定测试行
- linux - 检查作为 shell 脚本输入提供的可变数量的位置参数的有效性