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