javascript对忍者的新手无法获得书籍代码

时间:2015-03-13 23:47:03

标签: javascript css html5

我从SitePoint购买了一本看起来非常合法的电子书,但是当我完成代码(逐章)时,我已经在8章后陷入困境。这一点的代码按照规定工作,但我已经删除并重新编写了这个代码四次,并且不能在我的生活中找出在最后一次更改中发生的事情,其中​​提交框被替换为表单。

Codepen of related code http://codepen.io/anon/pen/RNezjb

//dom references//
var $question = document.getElementById("question");
var $score = document.getElementById("score");
var $feedback = document.getElementById("feedback");
var $start = document.getElementById("start");
var $form = document.getElementById("answer");

//view functio{ns
function update(element, content, klass) {
    var p = element.firstChild || document.createElement("p");
    p.textContent = content;
    element.appendChild(p);
    if(klass) {
        p.className = klass;
    }
}
quiz = {
"name":"Super Hero Name Quiz",
"description":"How many super heroes can you name?",
"question":"What is the real name of ",
"questions": [
    { "question": "Superman", "answer":"Clark Kent" },
    { "question": "Wonder Woman", "answer": "Diana Prince" },
    { "question": "Batman", "answer": "Bruce Wayne"}
]
};

//Event Listeners
$start.addEventListener("click", function () {
    play(quiz);
}, false);

function hide(element) {
    element.style.display = "none";
}
function show(element) {
    element.style.display = "block";
}
//play(quiz);
hide($form);
function play(quiz) {
    //hide button and show form
    hide($start);
    show($form);
    $form.addEventListener('submit', function(event) {
        event.preventDefault();
        check($form[0].value);
    }, false);
    var score = 0; //initialize score
    update($score, score);
    //main game loop
    var i = 0;
    chooseQuestion();
    function chooseQuestion() {
        var question = quiz.questions[i].question;
        ask(question);
    }
    //end of main game loop
    gameOver();
    function ask(question) {
        update($question,quiz.question + question);
        $form[0].value = "";
        $form[0].focus();
    }
    function check(answer) {
        if(answer ===quiz.questions[i].answer) {
            update($feedback,"Correct!","right");
            score++;
            update($score,score);
        }
        else {
            update($feedback,"Wrong!","wrong");
        }
        i++;
        if(i === quiz.questions.length) {
            gameOver();
        }
        else {
            chooseQuestion();
        }
    }
    function gameOver() {
        update($question,"Game Over, you scored " + score + " points");
        hide($form);
        show($start);
    }
}

我已经通过论坛查看了可能与本书代码有任何问题的其他人,但看起来这本书可能太新了(Javascript:Ninja的新手是大麻)让人们有类似的的问题。我已经在书中发现了一些印刷错误,但我觉得我的代码中有错误。

非常感谢任何帮助。我也无法在控制台中弹出任何错误。

由于

1 个答案:

答案 0 :(得分:0)

没关系,我实际上找到了两次调用gameOver()的地方,一旦我将它添加到checkAnswer函数中就不得不删除第一个实例。

由于