我正在学习JavaScript,这是我创建的第一个JavaScript函数,但它不起作用,我无法在此代码中找出问题:
<form method="post" name="answerForm" onsubmit="checkAnswer(document.answerForm.guessAnswer.value);">
<input type="text" name="guessAnswer" id="guessAnswer">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
var rightAnswer = 12;
function checkAnswer(guessAnswer) {
if (guessAnswer == rightAnswer) {
alert("You are right.");
}
else if (guessAnswer > rightAnswer) {
alert("You went too far.");
}
else if (guessAnswer < rightAnswer) {
alert("You're not even close to it.");
}
else () {
alert("I don't know what you talking about.");
}
}
</script>
答案 0 :(得分:1)
在你的功能中,你把其他地方放在空支架上是错误的。否则不需要它。请查看以下工作片段。
var rightAnswer = 12;
function checkAnswer(guessAnswer) {
if (guessAnswer == rightAnswer) {
alert("You are right.");
}
else if (guessAnswer > rightAnswer) {
alert("You went too far.");
}
else if (guessAnswer < rightAnswer) {
alert("You're not even close to it.");
}
else {
alert("I don't know what you talking about.");
}
}
<form method="post" name="answerForm" onsubmit="checkAnswer(document.answerForm.guessAnswer.value);">
<input type="text" name="guessAnswer" id="guessAnswer">
<input type="submit" name="submit">
</form>
答案 1 :(得分:0)
我可以看到您不想提交表单,因为表单标记中没有action
属性,您只想告知用户答案。
你应该使用onclick
事件,而不是然后提交,你也不需要表格。
只是
`<input type="button" name="submit" onclick="checkAnswer(document.answerForm.guessAnswer.value);">`
将完成这项工作
答案 2 :(得分:0)