试图在JS&amp ;;中进行能量转换。 HTML,得0

时间:2018-04-23 11:19:34

标签: javascript html

目标:寻求构建一个能够实现“热”的脚本。转换为' MWh'。为了做到这一点,用户将填写“' therm'输入框,点击“转换”按钮按钮和' 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>
&#13;
&#13;
&#13;

问题:无论用户在&#39; therm&#39;中输入的值如何,结果都为0。字段,我相信这是由var MWh确定的地方产生的。我似乎无法弄清楚这一点。有人可以帮我一把吗?

非常感谢, 拉尔夫

1 个答案:

答案 0 :(得分:1)

每次单击按钮时,您都不会更新计算。以下代码行运行的唯一时间:

false

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

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