简体   繁体   中英

Javascript onkeypress event fires but input text value is incorrect

I'm writing a simple javascript form that checks the input value against the value "blue". Now if you enter "blue", it says it's incorrect, but then if add any additional character, it says correct. It seems like there's a one-character delay, so when I enter "blue" it's only getting "blu". Here is the code:

<html>
<head>
<title>Favorite Color</title>
</head>

<body>
<h1>Quiz Time</h1>
<h2>What is your favorite color?</h2>

<p>Your Answer: <input type="text" id="txtinput" /></p>
<p id="message"></p>

<script type = "text/javascript">
function init() {
    var inp = document.getElementById("txtinput");
    inp.onkeypress=checkAnswer;

    checkAnswer();
}

onload = init;

function checkAnswer() {
    var text = document.getElementById("txtinput");
    var msg = document.getElementById("message");

    var sol = "blue";
    var ans = text.value;
    ans = ans.toLowerCase();

    if (ans.length <=0) {
        msg.innerHTML="<span style=\"color:blue;\">Enter Something.</span>";
    }
    else if (ans == sol) {
        msg.innerHTML="<span style=\"color:green;\">Correct!</span>";
    } else {
        msg.innerHTML="<span style=\"color:red;\">Wrong!</span>";
    }
}

</script>
</body>
</html>

将事件更改为onkeyup而不是onkeypress

inp.onkeyup=checkAnswer;

Use the HTML5 input event with a fallback to the propertychange event in IE < 9. I've written about this many times on SO; here are two examples:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM