javascript中的长度转换器

时间:2017-04-23 02:30:51

标签: javascript html function converter

[IMG] http://i.imgur.com/ch761kR.png[/img] 我必须重现如上图所示的长度转换器。当您在框中输入一个数字并按下一个按钮时,它会在您选择的按钮右侧显示结果。 我开始制作按钮。这是代码,我的问题是我不知道如何使一个函数在框外返回所选按钮的结果。

Valeur:<input type="text" name="valeur" value="0" oninput="LengthConverter(this.value)"onchange="LengthConverter(this.value)"> Resultat ici<br>
<button type="button" id="inchToCm" onclick="pvc()">Pouces vers cm</button>
<button type="button" id="cmtoInch">CM vers pouces</button>
<button type="button"id="celciusToFarenheit">Celcius vers
Farenheit</button>
    <button type="button" id="farenheitToCelcius">Farenheit vers Celcius</button>

我开始使用函数进行长度转换:

<script>
function pvc(valnum){
    document.getElementById("outputCm").innerHTML=valnum/0.39370;
}

</script>

提前感谢您的帮助

1 个答案:

答案 0 :(得分:2)

我为“Resultat ici”添加了一个带有id的p元素,以便可以从用户中检索该值。

Valeur:<input type="text" id="value" name="valeur" value="0" /> 

<p id="result">Resultat ici</p>

<button type="button" id="inchToCm" onclick="pvc()">Pouces vers cm</button>
<button type="button" id="cmtoInch" onclick="pvc()">CM vers pouces</button>
<button type="button"id="celciusToFarenheit" onclick="pvc()">Celcius vers
Farenheit</button>
<button type="button" id="farenheitToCelcius" onclick="pvc()">Farenheit vers 
Celcius</button>

我在下面的代码中为您做了第一次转换:

<script>
     function pvc() {  
        //get user's input
      var input = document.getElementById("value").value;

     /*implement if statement tests here for the next 3 buttons
      (cmtoinch, celctofahr, fahrtocelc)
      */

      //result of the calculation that is then put into the result p element with the id of result.
      var result = document.getElementById("result");
      result.innerHTML = input / 0.39370;

    }
</script>

此外,这是一个codepen示例:https://codepen.io/capozzic1/pen/MmeXxR

更新:codepen包含if语句