javascript没有工作onsubmit

时间:2016-10-03 09:33:32

标签: javascript html dom onsubmit

我正在学习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>

3 个答案:

答案 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)

在删除上一个else

的括号后,我的代码运行良好
else {
            alert("I don't know what you talking about.");
        }

请参阅演示here