摄氏和华氏转换器 - JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26046474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:25:00  来源:igfitidea点击:

Celsius and Fahrenheit Converter- JavaScript

javascriptjqueryhtmlconverter

提问by yolotheone

I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.

我想做一个有两个文本框的网页,一个摄氏度和华氏度框。在它们之间,有一个转换按钮,可以将摄氏度转换为华氏度,将华氏度转换为摄氏度。如果任一框中都有字母,我想取消转换并弹出一个警告说“请只输入数字!” 到目前为止,我还没有弄清楚如何获得警报,当我在摄氏度框中键入数字时,它总是在同一个框中显示数字 -18。华氏度没问题。

HTML:

HTML:

<html>
<head>
  <title>Temparature Converter</title>
  <script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
  Celsius: <input id="c" onkeyup="convert('C')">
  <button type="button" id="convert" onclick="convertTemp()">Convert</button>
  Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>

JavaScript:

JavaScript:

function convertTemp(degree) {
  if (degree == "C") {
    F = document.getElementById("c").value * 9 / 5 + 32;
    document.getElementById("f").value = Math.round(F);
  } else {
    C = (document.getElementById("f").value -32) * 5 / 9;
    document.getElementById("c").value = Math.round(C);
  }
}

Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.

注意:我从 W3Schools 得到了一些代码,所以我认为 onkeyup 转换有点有趣。如果可能,请通知我如何更改以及 JavaScript。

回答by Christopher Esbrandt

There is no need for the onkeyupattributes, since they original code from W3Schoolswas designed to instantly update values as they were entered.

不需要这些onkeyup属性,因为它们来自W3Schools 的原始代码旨在在输入值时立即更新值。

I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.

我确实修改了功能以清除原始值,这样转换按钮就可以通过简单的代码双向工作。

Here's a quick JavaScript to do the job:

这是一个快速的 JavaScript 来完成这项工作:

function convertTemp() {
 // Set the initial variables for c (Celsius) and f (Fahrenheit)
 var c = document.getElementById('c'), f = document.getElementById('f');
 // Test if there is a value for Celsius
 if(c.value != '') {
  // Set the value for Fahrenheit
  f.value = Math.round(c.value * 9 / 5 + 32);
  // Clear the value for Celsius
  c.value = '';
 // If there isn't a value for Celsius
 } else  {
  // Set the value for Celsius
  c.value = Math.round((f.value - 32) * 5 / 9);
  // Clear the value for Fahrenheit
  f.value = '';
 }
}

And its accompanying HTML:

及其随附的 HTML:

Celcius:<input id="c">&nbsp;&nbsp;&nbsp;
Fahrenheit:<input id="f">&nbsp;&nbsp;&nbsp;
<button type="button" id="convert" onclick="convertTemp()">Convert</button>

It can be tested at: http://jsfiddle.net/bhz6uz54/

可以在以下位置进行测试:http: //jsfiddle.net/bhz6uz54/

Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.

关于简单代码要记住的事情,像这样,没有什么可以验证提供的值是可接受的。一个小的正则表达式可以作为验证,但它如何实现取决于你想如何标记问题。

回答by Roko C. Buljan

I personally hate Do-itButtons so I'd go with a more dynamic solution:

我个人讨厌Do-itButtons,所以我会采用更动态的解决方案:

// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");

function FC_CF() {

  var temp;  // Will hold the temperature value
  var $targ; // Used to target the element we're not typing into:

  if (this.id === "c") { // If we're typing into #c...
    $targ = $f;          // use #f as target element
    temp = (this.value * 9 / 5) + 32;  // C2F
  } else {
    $targ = $c;
    temp = (this.value - 32) * 5 / 9;  // F2C
  }

  // Write the result "as we type" in the other ($targ) field:
  $targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1))  : "Err";
  // (Above:) temp is a num  ? return floated number,   else: "Show some error"

}

// Assign input listeners to trigger the above function:
$f.oninput = FC_CF; 
$c.oninput = FC_CF;
Celcius:    <input id="c">
Fahrenheit: <input id="f">

回答by Shaffic Muza

You can separate the functions which do the temperature conversion as follows i did somw changes in the code.

您可以按如下方式分离进行温度转换的函数,我在代码中做了一些更改。

       <p>
    <label>Fahrenheit</label>
  <input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
  oninput="temperatureConverterCelsius(this.value)"
  onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>

<input id="outputCelsius" type="number" placeholder="Celsius" 
   oninput="temperatureConverterFahrenheit(this.value)" 
    onchange="temperatureConverterFahrenheit(this.value)" value="">
    </p>


    <script type=""text/javascript>
    function temperatureConverterCelsius(valNum) {
    valNum = parseFloat(valNum);
    document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
    //document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;

}
    </script>


  </body>
</html>

回答by victor alfonso manco gonzalez

class Temperature_conversation {

    constructor(celsius) {

        this.celsius= celsius;
        this.fahrenheit= 0;
        this.table_begin= -50.0;
        this.table_end= 50.0;
        this.table_step= 10.0;
        console.log('---------------------Conversion--------------------------');
        console.log('Celsius fahrenheit');
        for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
            this.fahrenheit = this.celsiusToFahrenhit(celsius);
        }


    }
    celsiusToFahrenhit(c){
        const minimun_celsius = -273.15;
        if (c < minimun_celsius) {
            throw 'O argumento es pequeno';

        }
         this.celsius = (9.0 / 5.0) * c+ 32;

        var res = [this.celsius, this.fahrenheit]
        console.table(res);
    }
}