如何使用JavaScript中的函数转换温度

时间:2019-04-06 07:05:17

标签: javascript html

我想构建使用Java脚本中的任何功能将Temp从Celcius转换为Fahrenheit的代码 我想知道如何从window.prompt中获取值,并通过JavaScript中的任何函数将其用于进一步转换温度?

我创建了HTML,现在在JavaScript中我编写了window.prompt,可以在其中放置值。但是我无法弄清楚如何从window.prompt中获取此值,并通过使用函数将其转换为华氏度。

var button = document.getElementById('greeter-button');
button.addEventListener('click', function() {
  Temperature = window.prompt('What is temperature in celcius?');
});
<div id="button_and_text">
  <button id="greeter-button">Button!</button>
  <br> Click the button! Check the temperature!
  <br><br>
</div>

<div id="greeter-output"></div>

2 个答案:

答案 0 :(得分:1)

这是您的意思吗? 请注意,您通常需要将提示符返回的字符串转换为数字,例如使用+ temperature,但是乘法会为您将字符串转换为数字。运算符优先级在这里也有帮助

window.addEventListener("load", function() { // on page load
  var button = document.getElementById('greeter-button'),
      output = document.getElementById('greeter-output');
  button.addEventListener('click', function() {
    var temperature = window.prompt('What is temperature in celcius?');
    if (temperature != null) {
      output.innerHTML = temperature + "&deg;F = " + 
       (temperature * 9 / 5 + 32)    + "&deg;C";
    }  
  });
});
<div id="button_and_text">
 <button id="greeter-button">Button!</button><br/> 
 Click the button! Check the temperature!
</div>

<div id="greeter-output"></div>

答案 1 :(得分:1)

转换公式更为重要,一旦获得转换公式,就将其转换为数字并使用innerHTML

let button = document.getElementById('greeter-button');
button.addEventListener('click', function() {
  let temp = +window.prompt('What is temperature in celcius?');
  let f = ((9 * temp) / 5) + 32;
  document.getElementById('greeter-output').innerHTML = f
});
<div id="button_and_text">
  <button id="greeter-button">Button!</button>
  <br> Click the button! Check the temperature!
  <br><br>
</div>

<div id="greeter-output"></div>