如何在此脚本代码中正确设置此计算和变量

How to make this calculation and variables correct in this script code?

本文关键字:设置 计算 变量 脚本 代码      更新时间:2023-09-26

我觉得我进步了一点,当我被Javascript困住时,我仍然很难弄清楚该怎么做。这很难,但我需要紧急完成此编码。因此,非常感谢任何帮助。

这真的很简单,我想用开尔文、摄氏度和华氏度制作自己的转换器。所以我做了这 3 个变量,但我有点意识到它们需要自己的公式,所以我需要一个不同的变量来获得结果吗?如果是这样,它会去哪里?所有这些功能都令人困惑。这是我的代码。

        <form>
 Kelvin is
  <input id="kelvin" size="7" maxlength="5" type="text" placeholder="vul in" />
  <p></p>
  Celsius is
  <input id="celsius" size="7" maxlength="9" type="text" placeholder="vul in" />
  <p></p>
Fahrenheit is
<input id="fahrenheit" size="7" maxlength="9" type="text" placeholder="vul in" />
  <p></p>
  <input id="calculate" type="button" value="Bereken!" />
</form>

<div id="calc">Dit is kelvin
  <p></p>dit is celsius


dit 是华氏度

然后是脚本

<table cellSpacing=0 cellPadding=0 width=250 border=0>
document.getElementById('calculate').addEventListener('click', function() {

var kel= document.getElementById("kelvin").value;
var cel = document.getElementById("celsius").value;
var far = document.getElementById("fahrenheit").value;
var div = document.getElementById('calc');
if (( kel < 0 ||  cel < -273 || far < -459 ||  isNaN(kel) || isNaN(bev)) {
    div.innerHTML = "Not valid!";
    return;
  }
  kel = parseInt(kelvin); cel = parseInt(celsius); far = parseInt (fahrenheit);
  var far =  (cel * (9/5) + 35;
  var kel = cel + 273;
  var cel = kel - 273;
  var cel = (far -32)*(5/9);

  if (far = kel ) {
    var text = "hello? what to do here";
  }
 div.innerHTML = "Het is  <b>" + kelvin+ "</b> Kelvin <p></p> en het is <b>" + celcius + "</b>" en het is  <b>" + fahrenheit + "</b>";
 }, false); 

首先

if (far = kel ) {
    var text = "hello? what to do here";
}

应该是

if (far === kel ) {
    var text = "hello? what to do here";
}
=

用于定义变量,例如 var a = 10;

=== 用于比较两个值

另外,你把

<table cellSpacing=0 cellPadding=0 width=250 border=0>

在剧本中间。我希望这是一个错误。

哪个写得最好

<table cellspacing='0' cellpadding='0' width='250' border='0'>

符合更新的更严格的 XHTML 标准。

另外,这个:

if (( kel < 0 ||  cel < -273 || far < -459 ||  isNaN(kel) || isNaN(bev)) {
    div.innerHTML = "Not valid!";
    return;
}

需要替换为以下内容:

if ( kel < 0 ||  cel < -273 || far < -459 ||  isNaN(kel) || isNaN(cel) || isNaN(far)) {
    document.getElementById('calc').innerHTML = "Not valid!";
}

而这个:

 kel = parseInt(kelvin); cel = parseInt(celsius); far = parseInt (fahrenheit);

应为:

kel = parseInt(document.getElementById("kelvin").value); cel = parseInt(document.getElementById("celcius").value); far = parseInt (document.getElementById("fahrenheit").value);

Claies 也有一个很好的观点。

if(kel != ''){
    //Kelvin is the chosen one
}else if(far != ''){
    //Fahrenheit is the chosen one
}else if(cel != ''){
    //Celcius is the chosen one
}else{
    //User hasn't written anything
    alert('You need to write something to convert!');
}