如何切换功能javascript

时间:2017-03-23 18:28:47

标签: javascript function switch-statement

我想做点小事。当您输入摄氏度时,程序应计算华氏度,反之亦然。但是当我输入摄氏温度并单击按钮时,反之亦然。因为我是初学者,所以如果function1激活,我真的不知道怎么不执行function2。我的javascript看起来像这样:

JS:

function Omrekenen() {
  var celsius = document.getElementById('Celsius').value;
  var fahrenheit = document.getElementById('Fahrenheit').value;


  var r1 = (celsius * 1.8) + 32;
  var r2 = (fahrenheit / 1.8) - 32;
}

function Leeg1() {
  document.getElementById('Fahrenheit').value = "";
}

function Leeg2() {
  document.getElementById('Celsius').value = "";
}
<div class="Oefening">
  <h1 class="Titel">Oefening 3</h1>
  Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
  <input type="button" id="button3" value="Zet om" onclick="Omrekenen(); Vast();" class="Button">
</div>

2 个答案:

答案 0 :(得分:0)

这是实现此目的的一种方式。

请注意,我要检查输入值的长度。在这种情况下,您无法检查真实性(if (celsius) ...),因为0的值有效,但会评估为false。检查长度应适用于每种情况。

&#13;
&#13;
function Omrekenen() {
  var celsius = document.getElementById('Celsius').value;
  var fahrenheit = document.getElementById('Fahrenheit').value;

  if (celsius.length !== 0) {
      document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;      
  } else if (fahrenheit.length !== 0) {
      document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;          
  }
  
}

function Leeg1() {
  document.getElementById('Fahrenheit').value = "";
}

function Leeg2() {
  document.getElementById('Celsius').value = "";
}
&#13;
<div class="Oefening">
  <h1 class="Titel">Oefening 3</h1>
  Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
  <input type="button" id="button3" value="Zet om" onclick="Omrekenen();" class="Button">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您也可以使用状态变量,但在这种情况下您也想要处理粘贴操作。

<script>
var isCalculatingCelsius;
function Omrekenen()
{

  var celsius = document.getElementById('Celsius').value;
  var  fahrenheit = document.getElementById('Fahrenheit').value;


  if (isCalculatingCelsius){ 
    document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
  } else {
    document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
  }
}

function Leeg1(){
  isCalculatingCelsius = false;
  document.getElementById('Fahrenheit').value = "";
}

function Leeg2(){
  isCalculatingCelsius = true;
  document.getElementById('Celsius').value = "";
}

</script>
<div class="Oefening">
  <h1 class="Titel">Oefening 3</h1>
  Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup="Leeg1()">
  Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
  <input type="button" id="button3" value="Zet om" onclick="Omrekenen()" class="Button">
</div>