javascript 无法提交

javascript not working 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>

在您的函数中,您将 else 放在了空括号中,这是错误的。否则不需要它。请检查下面的工作片段。

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>

我看到您不想提交表单,因为表单标记中没有 action 属性,您只是想通知用户答案。

您应该使用 onclick 事件而不是提交然后您也不需要表单。

`<input type="button" name="submit" onclick="checkAnswer(document.answerForm.guessAnswer.value);">`

会完成工作

在最后删除括号后我让你的代码运行良好 else

else {
            alert("I don't know what you talking about.");
        }

观看演示 ​​here