【问题标题】:Factorial in a form with Java & HTML. What's wrong with my code?使用 Java 和 HTML 的表单中的阶乘。我的代码有什么问题?
【发布时间】:2021-01-01 19:04:12
【问题描述】:

我需要创建一个简单的表单,其中包含一个将数字计算为阶乘的按钮。计算必须通过按钮完成,并且需要在警告框中弹出答案。

不好意思,我已经尝试了好几个小时,但我无法让按钮工作,解决方法是按回车键,然后答案不显示。

<script>
var n = document.getElementById('x1').value;

function fac(N) {
  if (N > 1) return n * fac(N - 1);
  else return N;
}

alert("Answer is "+ fac(N));
</script>
<!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>factorial</title>
</head>

<body>
  <h2>Generate Your Factorial!</h2>
  <form>
  <label>Enter Number: </label><br>
  <input type="text" id="x1"><br>
  <input type="button"  value= "Generate" onclick="fac(N)">
  </form>
</body>

</html>

【问题讨论】:

  • onclick="fac(N)" ... N 未定义
  • 另外,var n = document.getElementById('x1').value; 只运行一次,在页面加载时,当该元素为空时 - 所以你也不能使用 n
  • 您确定您为此问题选择的标签吗?我认为这与html-helperjavahelp 没有任何关系...
  • 另外 JavaScript 与 Java 无关,您可能需要更新您的标题。您在单击时调用该函数,但 alert() 位于函数之外,并且在您单击按钮时不会被调用。

标签: javascript html html-helper


【解决方案1】:

我认为传递的值和函数中使用的值之间存在混淆,试试这样的方法

    <!DOCTYPE html>
    <html lang="en-US">

    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>factorial</title>
    </head>

    <body>
    <h2>Generate Your Factorial!</h2>
    <form>
    <label>Enter Number: </label><br>
    <input type="text" id="x1"><br>
    <input type="button"  value= "Generate" onclick="getFac()">
    </form>
    <script>
    
    
    function fac(N) {
      if (N > 1) {
          return N * fac(N - 1)
          }
      else{
           return N
      }
    }
    
    function getFac(){
        var n = document.getElementById('x1').value;
        alert("Answer is "+ fac(n));
    }
    
    </script>
  </body>

  </html>

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2017-01-21
    • 1970-01-01
    • 2012-09-15
    • 2019-06-06
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多