繁体   English   中英

尝试在JS和HTML中进行能量转换,获得0

[英]Attempting energy volume conversion in JS & HTML, getting 0

目标:寻求构建一个脚本,以将“ therm”转换为“ MWh”。 为此,用户将填写“热”输入框,单击“转换”按钮,“ MWh”值应显示在下方。

目前,我编写的代码如下:

 <p>Therm: <input type="number" id="thermid" name="therminput" /></p> <p> MWh: <span id="MWhid"></span></p> <p><input type="button" value="Submit" id="convertbutton" /></p> <script> var therm = document.getElementById("thermid").value; //This identifies the input field for therm var MWh = therm * 0.029307; //This determines the conversion from therm to MWh - something is wrong here //Below identifies when the button is clicked (eventlistener) then the 'innerHTML' displays the var MWh in the HTML field document.getElementById("convertbutton").addEventListener("click", function () { document.getElementById("MWhid").innerHTML = MWh; }) </script> 

问题:无论用户在“ therm”字段中输入什么值,结果均为0,我相信这是从确定var MWh位置得出的。 我似乎无法获得正确的答案。 有人可以帮我吗?

在此先感谢,拉尔夫

每次单击该按钮都不会更新计算。 只有以下几行代码运行:

var therm = document.getElementById("thermid").value;
var MWh = therm * 0.029307;

正在加载文档。 只需将它们放在事件处理程序中,以便每次单击按钮时它们的值都会更新。 即:

document.getElementById("convertbutton").addEventListener("click", function () {
  var therm = document.getElementById("thermid").value;
  var MWh = therm * 0.029307;
  document.getElementById("MWhid").innerHTML = MWh; 
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM