简单的JavaScript函数返回函数而不是值

one*_*one 1 javascript

我刚刚开始,我正在尝试构建一个简单的计算函数,它将在页面上显示2个数字的结果.当按下提交按钮时,输出是函数而不是值.我哪里出错了?

HTML

<div id="input">
<form id="start">
  <input id="price" type="number" placeholder="What is the starting price?" value="10">
  <input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
Run Code Online (Sandbox Code Playgroud)

JS

<script>
'use strict';

var total = function() {

  var price = function() {
    parseFloat(document.getElementById("price"));
  }

  var tax = function() {
    parseFloat(document.getElementById("tax"));
  }
  var final = function() {
    final = price * tax;
    final = total
  }

  document.getElementById("output").innerHTML = final;

};
</script>
Run Code Online (Sandbox Code Playgroud)

Fra*_*erZ 6

你的javascript有几个问题.让我们一个一个地分解它们:

var price = function() {
    parseFloat(document.getElementById("price"));
}
Run Code Online (Sandbox Code Playgroud)

document.getElementById返回一个元素.parseFloat会尝试计算元素,而不是这种情况下的值(总是NaN或非数字).您需要此元素的值,因此using .value将返回该值.而且,你实际上并没有做任何有价值的事情.(您应该使用return返回找到的浮点数,或将其设置为另一个变量.)

var final = function() {
   final = price * tax;
   final = total
}
Run Code Online (Sandbox Code Playgroud)

price并且tax在这种情况下都是功能.你不能简单地将它们相乘以得到你想要的结果.使用var total = price() * tax();设置变量total从返回的浮动price()tax()现在.将此值返回到函数将修复下一行:

document.getElementById("output").innerHTML = final;
Run Code Online (Sandbox Code Playgroud)

final这里也是一个功能.你想用它来调用它final().

你的最终剧本:

var total = function() {

  var price = function() {
    return parseFloat(document.getElementById("price").value);
  }

  var tax = function() {
    return parseFloat(document.getElementById("tax").value);
  }
  var final = function() {
    var total = price() * tax();
    return total
  }

  document.getElementById("output").innerHTML = final();

};
Run Code Online (Sandbox Code Playgroud)
<div id="input">
  <form id="start">
    <input id="price" type="number" placeholder="What is the starting price?" value="10">
    <input id="tax" type="number" value="0.08" step="0.005">
  </form>
  <button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
Run Code Online (Sandbox Code Playgroud)