球体体积计算器

时间:2018-11-06 05:17:48

标签: javascript calculator volume

您好,我正在制作音量计算器,但似乎无法将音量显示在屏幕上。发出警报会解决此问题吗?这项工作要求我使用匿名函数,因此我很难让该函数运行。

HTML
 <body>
 <h3> Calculate the Volume of a Sphere <h3>
 <label for="radius">Radius </label>
 <input id="radius" name="radius"  required>
 </input>

 <button id="calc" onclick=sphereVol> calculate </button>

JavaScript

 var sphereVol = function(radius){
 var c = (4/3) * Math.PI * Math.pow(radius, 3);
 return c;
 }

3 个答案:

答案 0 :(得分:1)

您需要操纵DOM来接收输入并显示输出。您的功能是正确的,但这是操作DOM的一种方法:

HTML

<body>
 <h3> Calculate the Volume of a Sphere <h3>
 <label for="radius">Radius </label>
 <input id="radius" name="radius" required>

 <button id="calc" onclick=sphereVol()> calculate </button>

 <p>Your volume:</p>
 <p id="outputVolume"></p>

JavaScript

 var sphereVol = function(){
    var radius = document.getElementById("radius").value;
    var c = (4/3) * Math.PI * Math.pow(radius, 3);

    document.getElementById("outputVolume").innerHTML = c;
 }

发生了什么变化

  • 我说sphereVol
  • 来调用onclick sphereVol()中的函数
  • 我查了一下音量
  • 我更改了HTML以显示结果

进一步阅读:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
  2. https://www.w3schools.com/jsref/prop_text_value.asp
  3. https://www.w3schools.com/js/js_htmldom_html.asp

答案 1 :(得分:1)

程序中有几个错误。我改进了您的代码,并阅读了每一行中的注释。

<html>
 <body>
 <h3> Calculate the Volume of a Sphere <h3>
 <label for="radius">Radius </label>
 <input id="radius" name="radius"  required>
 </input>
 <!-- I added double quote around sphereVol variable which holds the annonymous function  and also have to provide parenthesis for it. -->
 <button id="calc" onclick="sphereVol()"> calculate </button>
 <p id="result"></p>
<script>

 var sphereVol = function(){
 //Reading input radius here
 radius = document.getElementById("radius").value;
 var c = (4/3) * Math.PI * Math.pow(radius, 3);
 console.log(c);
 document.getElementById("result").innerHTML="The volume is: "+c;
 }
 </script>
 </body>
</html>

答案 2 :(得分:0)

您需要在某处从输入和输出获取半径。您可以使用alert()console.log(),但是可以输出到页面更好。 document.getElementById()是从DOM中获取元素的基本方法,而value可以帮助获取输入。这是一个超级简化的版本:

var sphereVol = function() {
  // get the radius
  let radius = document.getElementById('radius').value
  var c = (4 / 3) * Math.PI * Math.pow(radius, 3);
  // display the result
  document.getElementById('result').textContent = "Volume ≈ " + c.toFixed(4);
}
<h3> Calculate the Volume of a Sphere
</h3>
<label for="radius">Radius </label>
<input id="radius" name="radius" required>
</input>

<button id="calc" onclick="sphereVol()"> calculate </button>
<div id="result">
</div>