【发布时间】:2016-12-23 18:18:01
【问题描述】:
好的,我正在尝试创建测验应用程序,我已经花了 8 多个小时试图找出问题所在。我只是放弃,所以如果可以的话,请帮助我。情况是我使用 DOM 创建单选输入,您可以选择选择问题的答案,每次单击下一步时,div 标签中会显示另一个问题,而之前的 div 标签被删除。我想以一种方式存储结果,在完成所有问题后,我会在警报窗口中通知用户,或者有多少被正确回答。问题是我找不到我做错了什么。
answers = document.getElementsByName('quiz');
if(answers[1].checked){
alert("gj");
}
这在浏览器控制台中运行良好,如果用户选择了 1 号单选按钮,它会提醒我。但是当我把它放在我的脚本中时,它什么也不做。 我猜问题出在我如何创建整个 start() 函数的某个地方,但我无法理解它。
完整代码: 动态测验
var allQuestions = [{
question: "Question1?",
choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
CorrectAnswer:0},
{
question: "Question2?",
choices: ["Answer6", "Answer7"],
CorrectAnswer:0}
];
var currentQuestion=0;
var currentAnswer=0;
var correctAnswer=0;
var answers;
var div2;
function createDiv(){
var div=document.createElement("div");
div2=document.getElementById("content").appendChild(div);
}
function createQuestion(question){
var q = document.createElement('p');
q.innerHTML=question;
div2.appendChild(q);
}
function createRadio(id){
var radio = document.createElement('input');
radio.setAttribute("type","radio");
radio.setAttribute("name","quiz");
radio.setAttribute("id",id);
div2.appendChild(radio);
}
function createLabel(id,text){
var lab = document.createElement('label');
lab.setAttribute("id",id);
lab.setAttribute("for",id);
lab.innerHTML=text;
div2.appendChild(lab);
}
function checkAnswer(){
answers = document.getElementsByName('quiz');
if(answers[1].checked){
alert("gj");
}
}
function remover(){ //removes content for next question
var myNode = document.getElementById("content");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function start(){
remover();
createDiv();
createQuestion(allQuestions[currentQuestion].question);
//create all radio answers for question in div
for (var i = 0; i<allQuestions[currentQuestion].choices.length;i++){
createDiv();
createRadio(allQuestions[currentQuestion].choices[i]);
createLabel(allQuestions[currentQuestion].choices[i],allQuestions[currentQuestion].choices[i]);
}
checkAnswer();
currentQuestion++;
if (currentQuestion === allQuestions.length){ //just sto stop from going infinite
currentQuestion=allQuestions.length-1; }
}
</script>
</head>
<body onload=start()>
<div id="main">
<div id="content"></div>
</div>
<div id="butn">
<input type="submit" value="Start" onClick="start()">
</body>
</html>
【问题讨论】:
标签: javascript html