简体   繁体   English

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

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

Objective: Looking to build an script which enables 'therm' to be converted to 'MWh'. 目标:寻求构建一个脚本,以将“ therm”转换为“ MWh”。 In order to do so, the user would fill out the 'therm' input box, click the 'convert' button and the 'MWh' value should appear below. 为此,用户将填写“热”输入框,单击“转换”按钮,“ MWh”值应显示在下方。

Currently the code I have written is as follows: 目前,我编写的代码如下:

 <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> 

Problem: The result is 0 regardless of the value that the user enters in the 'therm' field and I believe this is resulting from where var MWh is being determined. 问题:无论用户在“ therm”字段中输入什么值,结果均为0,我相信这是从确定var MWh位置得出的。 I don't appear to be able to get this correct. 我似乎无法获得正确的答案。 Could someone give me a hand? 有人可以帮我吗?

Many thanks in advance, Ralph 在此先感谢,拉尔夫

You are not updating the calculation every time the button is clicked. 每次单击该按钮都不会更新计算。 The only time the following lines of code are run: 只有以下几行代码运行:

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

are on the document load. 正在加载文档。 Simply place them inside the event handler, so that their values get updated every time you click the button. 只需将它们放在事件处理程序中,以便每次单击按钮时它们的值都会更新。 Ie: 即:

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