我正在尝试输出到控制台的简单程序。一切都很好,只是意外的未定义,我不知道为什么我得到它。任何人请解释什么是错的,我怎样才能使我的代码更好。感谢
var next = document.getElementById('next');
var questions =
[
{
question: "Color of sky is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 2
},
{
question: "Color of milk is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 1
},
{
question: "Color of Grass is ?",
choices: ["Green","White", "Blue", "Red"],
answer: 0
}
];
var counter = 0;
function loadQuestion () {
var obj = questions[counter];
var quest = obj.question;
var choice = obj.choices;
function options() {
choice.forEach(function(val){
console.log(val);
return false;
});
}
var answer = obj.answer;
counter++;
console.log ( " Question : " + quest );
console.log( options() );
console.log( answer );
}
next.onclick = function() {
if ( counter < questions.length ) {
loadQuestion();
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="quiz-container">
<button id="next"> Next Question </button>
</div>
</body>
</html>
答案 0 :(得分:2)
你为什么这样做:
console.log( options() );
在options
函数中,您已经打印了选项,因此您应该仅使用以下内容替换此行:
options();
如果您想知道为什么它的打印undefined
因为options
函数没有返回任何内容(return false只是每个项目的forEach回调的返回值),如果您执行以下操作,它将打印{ {1}}代替true
:
undefined
示例:
function options() {
choice.forEach(function(val){
console.log(val);
return false;
});
return true;
}
答案 1 :(得分:0)
options()
---snip---
console.log('Question: ' + quest);
options(); // print options
console.log('Answer: ' + answer);
---snip---
有很多方法可以从您的选择列表中生成单选按钮。我在下面提供了一种我喜欢使用的方式。
我假设你的表单中有一个`按钮元素
--- snip ---
function generateQuestion(parent, question) {
var h3_ = document.createElement('h3');
var question_ = document.createTextNode(question);
h3_.appendChild(question_);
parent.insertBefore(h3_, parent.firstChild);
}
function generateOptions(parent,options) {
options.forEach(function(val){
parent.insertBefore(
makeSpan(makeRadioButtons('choice',val), val),
parent.firstChild // the button element
);
});
}
function makeRadioButtons(name_, value_) {
var radio_b = document.createElement("input");
radio_b.setAttribute('type','radio');
radio_b.setAttribute('name',name_);
radio_b.setAttribute('value',value_);
return radio_b;
}
function makeSpan(radio_button, value) {
var span_ = document.createElement('span');
var text_ = document.createTextNode(value);
span_.appendChild(radio_button);
span_.appendChild(text_);
return span_;
}
//get my form
var my_form = document.getElementById('my_form');
function loadQuestion() {
---snip---
generateOptions(my_form, choice);
generateQuestion(my_form, quest);
---snip---
}
使用字符串有更多方法,但我发现以后很难维护。 以下是上面提供的代码的工作示例:https://jsfiddle.net/04hruhyo/