如何在 HTML 中的外部 Javascript 文件中使用函数?

How to use a function in an external Javascript file in HTML?

这是我第一次使用外部 Javascript 文件。我正在做关于 Javascript 的 murach 系列书籍中的练习,我被困在一些非常基本的事情上。我将展示我所做的 Javascript 编码,然后我将展示 html 文件。每当我单击按钮计算未来值时,它什么都不做,即使我有 onload 事件处理程序。

   /*Javascript*/
    var $ = function(id) {
return document.getElementById(id);
};

    function calculateFV(investment, interest, years) {]{

    investment =  $("investment").parseFloat($("investment").value);
    interest =  $("annual_rate").parseFloat($("annual_rate").value);
    years = $("years").parseInt($("years").value);

   var cInterest = investment * interest;

   cInterest = parseFloat(cInterest);
             futureValue = parseFloat(futureValue);
        for (var i = 1; i < years; i++) {
            investment = investment + (cInterest / 100);
             }
           investment = parseFloat(investment).toFixed(2);
                
   $ ("future_value") = investment;
}

window.onload = function() {
$("calculate").onclick = calculateFV;
$("investment").focus();
 };
 /* End of Javascript */

  /* HTML */
  <!DOCTYPE html>
  <html>
  <head>
      <meta charset="UTF-8">
      <title>Future Value Calculator</title>
      <link rel="stylesheet" href="future_value.css">
      <script src="future_value.js"></script>
  </head>

    <body>
        <main>
          <h1>Future Value Calculator</h1>
    
          <label for="investment">Total Investment:</label>
          <input type="text" id="investment">
          <span id="investment_error">&nbsp;</span><br>
    
          <label for="rate">Annual Interest Rate:</label>
          <input type="text" id="annual_rate">
          <span id="rate_error">&nbsp;</span><br>
    
          <label for="years">Number of Years:</label>
          <input type="text" id="years">
          <span id="years_error">&nbsp;</span><br>
    
          <label for="future_value">Future Value:</label>
          <input type="text" id="future_value" disabled><br>
    
          <label>&nbsp;</label>
          <input type="button" id="calculate" value="Calculate"><br>      
      </main>
      </body>
      </html>

    /* End of HTML */

不管您的代码中有哪些印刷错误,我想提一下您还犯了其他一些错误:

  1. parseInt()是一个函数;不是一种方法。因此它必须作为一个函数来使用。像这样:investment = parseFloat($("investment").value); 而不是:
    investment = $("investment").parseFloat($("investment").value);

  2. $("future_value") 是文本框;不是它的价值。要真正让某些东西出现在 $("future_value") 中,您必须说:$("future_value").value = investment.

  3. 您的 calculateFV() 函数不应有任何参数。 Investmentinterestyears 是函数内部的局部变量,因此您的函数不需要任何输入。

  4. 你解析的太多了,粗心大意。在您的代码中您说:cInterest = parseFloat(cInterest);futureValue = parseFloat(futureValue);
    • 我们使用 parseFloat() 来解析字符串。上述变量包含数学运算后出现的算术值,而不是字符串。因此你不需要解析它们。

我创建了一个 jsFiddle,您的代码已更正并正常运行。你可以找到它 here.

祝你学习顺利☺