Javascript 新手到忍者无法让书籍代码工作

javascript novice to ninja can't get book code to work

本文关键字:代码 工作 新手 忍者 Javascript      更新时间:2023-09-26

我从SitePoint购买了一本电子书,看起来很合法,但是当我(逐章)学习代码时,我在8章后陷入困境。 到目前为止,代码已按规定工作,但是我已经删除并重新设计了此代码四次,并且我一生都无法找出提交框被表单替换的最后更改中发生了什么。

相关 codehttp://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("answerswer");
//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", "answerswer":"Clark Kent" },
    { "question": "Wonder Woman", "answerswer": "Diana Prince" },
    { "question": "Batman", "answerswer": "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:新手到忍者是大部头),人们没有类似的问题。 我已经在书中发现了一些印刷错误,但我有一种感觉,我的代码中有一些错误。

任何帮助将不胜感激。 我也无法在控制台中弹出任何错误。

谢谢

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

谢谢