javascript - 尝试创建一个数学游戏

标签 javascript jquery html

我在下面为一个简单的数学游戏修改/编辑了代码。您输入要解决的金额,然后解决!

我现在遇到的问题是,在最后,它只显示分数。

我试图让它不仅显示分数,还显示您输入要解决的问题数量。因此,它更像是一个“你得到了”分数“超出”输入正确的问题。下面是代码和 Fiddle 的链接。

http://jsfiddle.net/justinw001/Mttw6/12/

$(function () {
    var score = 0;
    var questions = [];
    $('#gen').click(function () {
        score = 0;
        questions = [];
        var questionAmount = parseInt($('#inputElement').val(), 10);
        for (var i = 0; i < questionAmount; i++) {
            var q = {
                x: Math.floor(Math.random() * 13),
                y: Math.floor(Math.random() * 13)
            };
            questions.push(q);
        }
        nextQuest(questions.pop());
    });
    $('#sub').click(function () {
        var ans, x, y;
        if (questions.length >= 0) {
            ans = parseInt($('#answer').val(), 10);
            x = parseInt($('#input1').text(), 10);
            y = parseInt($('#input2').text(), 10);
            if (ans === x * y) {
                score++;
            }
            nextQuest(questions.pop());
        }
    });
    var nextQuest = function (q) {
        if (q) {
            $('#input1').text(q.x);
            $('#input2').text(q.y);
            $('#answer').val('');
            $('#inputElement').val(questions.length);
        } else {
            $('#input1, #input2').text('');
            $('#answer, #inputElement').val('');
            alert(score);
        }
    };
});

最佳答案

在函数外声明questionAmount

$(function () {
    var score = 0;
    var questions = [];
    var questionAmount=0; //here
    $('#gen').click(function () {
        score = 0;
        questions = [];
        questionAmount = parseInt($('#inputElement').val(), 10);

然后当你提醒时这样做

 alert(score+" out of "+questionAmount + " correct");

DEMO

关于javascript - 尝试创建一个数学游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434387/

相关文章:

javascript - 如何在 jQuery 中使用过滤器链接多个选择器?

html - div 背景没有出现在 live ie 和 firefox 中

html - HTML/CSS 文本下的行

javascript - AJAX 页面重新加载

php - 如何使帖子日期同步

javascript - Angular - 在加载路由器之前获取路由器 url

jquery - 针对特殊要求的 JSF 2.0 与 Wicket 与 SpringMVC 3.x

javascript - jQuery Validation插件——关闭基于类属性的验证

javascript - 将鼠标悬停在同一表格中的另一行上时更改表格行的背景颜色

javascript - 如何编写正则表达式来匹配不跟随另一个 "\n"的 "\n"?