我正在寫一個簡單的javascript窗體,檢查輸入值與「blue」值。現在,如果輸入「藍色」,則表示它不正確,但如果添加任何其他字符,則說明正確。似乎有一個字符延遲,所以當我輸入「藍色」時,它只會變成「藍色」。下面是代碼:Javascript onkeypress事件觸發但輸入文本值不正確
<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>
你試試我的答案? – 2012-02-19 13:47:55
是的,它的工作,謝謝! :) – CaptainCodeman 2012-02-19 15:54:05