首页 > 解决方案 > 使用 javascript 声明多个函数时未定义的匿名函数

问题描述

我是 JS 新手,正在尝试使用匿名函数。我有两个简单的匿名函数,它们本身就可以完美地工作,但是一旦我将它们都放在脚本中,我就会收到“ReferenceError:checkAnswer_js 未定义”消息。为什么会这样?

所以基本上我有一个输入和三个按钮。第一个按钮检查输入值是否与设定值匹配,如果匹配,则启用第二个按钮发送输入值。最后一个按钮充当另一个页面的链接:

function checkAnswer_js() {
    var formulaAlpha = "5 + 5";//TEST
    var x = eval(formulaAlpha);
    if (document.getElementById('answer').value == x) {
        document.getElementById('send').disabled = false;
    } else document.getElementById('send').disabled = true;
}
function index_js() {
    if (confirm('Are you sure you want to return to index?')) {window.location.href = 'index.html';}
}
<div id="expresionfinal">5 + 5?</div>
<form name="lastform" method="POST" action="formulariofinal.php" accept-charset="utf-8" id="finalform" onsubmit="confirm('Are you sure you want to submit the answer?');">
  <div>
    <input type="text" name="sent-answer" required id="answer" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
  </div>
  <div>
    <button type="button" onclick="checkAnswer_js();">Check answer</button>
  </div>
  <div>
    <button type="submit" id="send" disabled>Submit</button>
  </div>
</form>

<div>
  <button onclick="index_js()">Return to index</button>
</div>

单击按钮时出现错误。

编辑:更正了语法问题。似乎代码在这里工作得很好。但在我的 xampp 服务器中,它仍然给我错误。我的代码在那里更大,但我想简化问题。某处的语法错误是否可能会阻止正确定义函数?

标签: javascriptfunctionanonymous-function

解决方案


推荐阅读