javascript - 球体体积计算器

标签 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;
 }

最佳答案

您需要操作 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

关于javascript - 球体体积计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166115/

相关文章:

opengl - 获取在 OpenGl 中可以看到的所有内容的边界框

javascript - 我需要使用 javascript 将 "flat"json 对象转换为具有一对多匹配能力的嵌套 json 树

java - 后缀堆栈计算器

audio - 如何在OpenAL中设置 channel 增益?

android - 我如何在 Textview setText Android 上进行计算

Python def 标记为无效语法

ios - 在 ios 中使用 AVSystemController 获取铃声音量级别

javascript - .click 不适用于图形中的 anchor

javascript - 动态更改 SharePoint 2013 搜索代码段中的内容

javascript - 当浏览器选项卡中的 URL 更改时自动注销