期望的结果:用户选择答案后,我想修改以下位置的score
变量:
如果答案正确,score += 1
;如果答案错误,则根本不改变。
当前结果:对于用户做出的每个选择,分数保持不变:0
。
首先,我将要更改的段落存储在 question_paragraph
中,并将用户单击的按钮存储在 next_button
中。另外,我将值存储在 user_answer
中(我使用数组符号将属性 value
放在每个输入上 - 首先是 0,1 秒等)。
var question_paragraph = document.getElementById('question');
var next_button = document.getElementById('next');
var i = 0;
var user_answer = getCheckedValue(document.getElementsByName('choice'));
var y = 0;
var score = 0;
getCheckedValue
函数将返回我输入的 value
属性(如果存在)。
function getCheckedValue(radioObj) {
var radioLength = radioObj.length;
for(var z = 0; z < radioLength; z++) {
if(radioObj[z].checked) {
return radioObj[z].value;
}
}
return "Error!";
}
这是问题。除了隔离区域外,该功能运行良好。 allQuestion
是我存储问题、可能的答案和正确答案 CorrectAnswer
的对象(我没有将其包含在此处,但可以正常工作)。我添加了一个条件语句,如果 allQuestions[y]. CorrectAnswer
与 user_choice
的值相等,则将 y
和 code>score 增加 1 >.
function changeQuestion() {
//PROBLEM
if(allQuestions[y].correctAnswer == user_answer){
score += 1;
y++;
} else{y++;}
//PROBLEM
i = (i < allQuestions.length) ? (i + 1) : 0;
if (i == allQuestions.length) {
i = 0;
return question_paragraph.replaceChild(document.createTextNode(allQuestions[0].question), question_paragraph.firstChild);
}
var newNode = document.createTextNode(allQuestions[i].question);
console.log(score);
return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}
最后,我调用了 addHandler
函数。
function addHandler(name, type, handler){
if (name.addEventListener){
name.addEventListener(type, handler, false);
} else if (name.attachEvent){
name.attachEvent("on" + type, handler);
} else {
name["on" + type] = handler;
}
}
addHandler(next_button, 'click', changeQuestion);
最佳答案
嗯,到目前为止,有些事情似乎很有趣。首先,我没有看到变量 y 有任何初始化。如果 y 是保留其值的全局变量,那么您的对象可能存在问题:allQuestions{}。您能否提供构建对象 allQuestions{} 的代码?没有它,我认为我无法完全回答这个问题,但我相信这就是您的问题所在。
哎呀,这应该是评论,而不是答案,抱歉......
关于javascript - 事件发生后将分数存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24491141/