在CodePen - http://codepen.io/PartTimeCoder/pen/WwMxEX?editors=0010中指向我的笔的链接
Javascript在这里:
function randomNum(digits) {
return Math.floor(Math.pow(10, digits - 1) + Math.random() * 9 * Math.pow(10, digits - 1));
}
function askQuestion(digits) {
$(".result").html("");
var factor1 = randomNum(digits);
var factor2 = randomNum(digits);
var correctanswer = factor1 * factor2;
var answer = parseInt($(".answer").val(), 10);
console.log(correctanswer);
$(".question").html(factor1 + " × " + factor2);
var score = 0;
//Problem Starts Here
$(".check").click(function() {
if (correctanswer == answer) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});
//Problem Ends Here
}
$(document).ready(function() {
$(".answer").hide();
$(".check").hide();
var digits = 0;
$(".digits-1").click(function() {
digits += 1;
});
$(".digits-2").click(function() {
digits += 2;
});
$(".digits-3").click(function() {
digits += 3;
});
$(".btn").click(function() {
$(".btn").hide();
$(".answer").show();
$(".check").show();
askQuestion(digits);
});
});中间的评论是我认为的问题所在。例如,当它要求4x9和我输入36时,它仍然将其标记为错误。我不知道为什么要这么做。起初,我认为输入的信息可能仍然是一个字符串,所以我在它上使用了parseInt,但它仍然不起作用。所有的帮助都是感激的。提前感谢!
发布于 2016-04-10 21:36:48
问题是在$('.answer')变量中缓存answer元素的初始值。当您执行$('.answer').val()时,它保存了当时的是什么,所以如果用户后来更改了他们的答案,它将不会反映在您的变量中。你想做的是这样的事情:
// Rest of your code above
var answer = $(".answer");
console.log(correctanswer);
$(".question").html(factor1 + " × " + factor2);
var score = 0;
//Problem Starts Here
$(".check").click(function() {
// Don't check what is in the input until you're ready to use the value.
if (correctanswer == parseInt(answer.val(), 10)) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});发布于 2016-04-10 21:37:08
单击处理程序有一个对旧答案值的引用。每次都必须从输入中获取值。就像这样:
$(".check").click(function() {
var answer = parseInt($(".answer").val(), 10);
if (correctanswer == answer) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});https://stackoverflow.com/questions/36535779
复制相似问题