您好,我正在制作一个音量计算器,但我似乎无法在屏幕上显示音量。发出警报可以解决这个问题吗?这项作业要求我使用匿名函数,因此我很难让该函数运行。
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;
}
最佳答案
您需要操作 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()
在 onclicksphereVol
中调用了该函数 - 我查了一下音量
- 我更改了 HTML 以显示结果
进一步阅读:
关于javascript - 球体体积计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166115/