gpt4 book ai didi

javascript - 将测验问题存储在对象数组中

转载 作者:行者123 更新时间:2023-11-30 16:04:26 26 4
gpt4 key购买 nike

我正在尝试用 JavaScript 创建一个小测验程序。所有的问题都包含在数组中,每个问题都是一个包含问题本身的对象,供用户选择和回答的选项。 Quiz 循环遍历所有问题数组并打印问题和选项供用户选择。我希望选择是单选按钮。我正在努力弄清楚如何用问题选择文本填充单选按钮。知道怎么做吗?

      var userChoices = document.getElementsByTagName('input[type:radio]');
var questions =
[
{
question: "What is the capital of United Kingdom?",
choices: ["Manchester", "Birmingham", "London", "Birmingham"],
answer: 2
},

{
question: "What is the capital of United States?",
choices: ["California", "New York", "Miami", "Florida"],
answer: 1
}


];

for ( var i = 0; i < questions.length; i++ ) {
var question = questions[i].question;
document.write ( question );
var options = questions[i].choices;
for ( var opt in options ) {
for ( var radios in userChoices ) {
userChoices[radios].value = options[opt];

}
}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>

<input type="radio" name="choices"><br>
<input type="radio" name="choices"><br>
<input type="radio" name="choices"><br>
<input type="radio" name="choices"><br>

</body>
</html>

最佳答案

您可以像下面这样简化您的 JS 代码:

      var questions = 
[
{
question: "What is the capital of United Kingdom?",
choices: ["Manchester", "Birmingham", "London", "Birmingham"],
answer: 2
},

{
question: "What is the capital of United States?",
choices: ["California", "New York", "Miami", "Florida"],
answer: 1
}


];

for ( var i = 0; i < questions.length; i++ ) {
var question = questions[i].question;
document.write ( question );
var options = questions[i].choices;
document.body.appendChild(document.createElement("br"));
var name = "radio"+i;
for ( var opt in options ) {

var radioEle = document.createElement("input");
radioEle.type = "radio";
radioEle.value = options[opt];
radioEle.name = name;
document.body.appendChild(radioEle);
var label = document.createElement("Label");
label.innerHTML = options[opt];
document.body.appendChild(label);
document.body.appendChild(document.createElement("br"));
}

document.body.appendChild(document.createElement("br"));

}

关于javascript - 将测验问题存储在对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37252041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com