-1

please forgive the very amateur code, as I only very recently started doing HTML/Javascript, etc.

I'm making a quiz-type application for air traffic controllers here. They type in the correct answer in the text input box, and the datablock changes to reflect the new altitude. When I try it, it works beautifully. But when I start trying to use a counter to track correct and incorrect responses, after the first answer, the counter will always log an incorrect response first, and then immediately after, a correct response. So if they answered 2 questions correctly, the quit button will show they got 2 questions right, and 1 question wrong.

Here's my code:

<script>
var correctAns = 0;
var incorrectAns = 0;


var newProblem = function() {
var AircraftData = new Aircraft();
$("#altitudeLine").focus();
$("#problem").html(AircraftData.newAlt);
$("#callsign").html(AircraftData.callsign);
$("#altitudeLine").html(AircraftData.initAltitude + "C");
$("#aid").html(AircraftData.aid);
$("#speed").html(AircraftData.speed);
$("#altInput").focus();

$(document).keydown(function(e) { 
    var correctAnswer = "QQ" + " " + AircraftData.newAlt + " " + AircraftData.aid;
    var userAnswer = $("#altInput").val().toUpperCase();
    if (e.which == 13) {
        if (correctAnswer == userAnswer) {
            $("#feedback").html("Correct!");
            $("#altitudeLine").html(AircraftData.newAlt + "T" + AircraftData.initAltitude);
            correctAns++;
            return;
        }
        else {
            $("#feedback").html("Incorrect!");
            incorrectAns++;
            return;
        }
    }       
});
}


function clearProblem() {
$("#feedback").html("");
$("#altInput").val("");
$("#altInput").focus();
setTimeout(newProblem(), 2000);
}

function results() {
alert("Correct: " + correctAns + " | Incorrect " + incorrectAns);
}
</script>
</head>

// stripped out a lot of code not relevant

<button onClick="newProblem()">Start</button>
    <button id="next" onClick="clearProblem()">Next</button>
    <span id="problem"></span>
    <input type="text" id="altInput">
    <span id="feedback"></span>
    <br />
    <button id="quitButton" onClick="results()">Quit</button>
</div>
4

1 回答 1

1

After fixing some of the code, I realized your problem: you are defining a new event handler for the keydown event with every new problem, never removing the old event handler.

You should use off() to remove the existing handler and on() to set the new one so there's always only one:

$(document).off('keydown');
$(document).on('keydown', function () { ... });

But do you really need to redefine the event handler with every new problem? The only thing that's changing is the correctAnswer value to compare with. You should really define the handler once, and have it dynamically determine the correctAnswer value.

于 2013-05-06T16:31:07.683 回答