JavaScript不会更新输入

时间:2019-06-22 01:10:05

标签: javascript html

我正在尝试创建一些温度转换器,但是我不能这样做,因为innerHTML不会更新“输入框”中的值。

我使用了一些console.log来检查valID和valNum的值,但是看起来都不错,所以我不明白为什么代码不起作用。

<body>
    <h2><u>Temperature Converter</u></h2>

    <p>
        <label>Fahrenheit</label>
        <input id="fahrenheit" type="number" placeholder="Fahrenheit" onchange="tempConverter(this.id, this.value)" oninput="tempConverter(this.id, this.value)">
    </p>

    <p>
        <label>Celsius</label>
        <input id="celsius" type="number" placeholder="Celsius" onchange="tempConverter(this.id, this.value)" oninput="tempConverter(this.id, this.value)">
    </p>

    <p>
        <label>Kelvin</label>
        <input id="kelvin" type="number" placeholder="Kelvin" onchange="tempConverter(this.id, this.value)" oninput="tempConverter(this.id, this.value)">
    </p>

    <script>
        function tempConverter(valID, valNum)
        {
            valNum = parseFloat(valNum);
            if (valID === "fahrenheit")
            {
                document.getElementById("celsius").innerHTML = (valNum - 32) / 1.8;
                document.getElementById("kelvin").innerHTML = ((valNum - 32) / 1.8) + 273.15;
            }
            if (valID === "celsius")
            {
                document.getElementById("fahrenheit").innerHTML = (valNum * 1.8) + 32;
                document.getElementById("kelvin").innerHTML = valNum + 273.15;
            }
            if (valID === "kelvin")
            {
                document.getElementById("fahrenheit").innerHTML = ((valNum - 273.15) * 1.8) + 32;
                document.getElementById("celsius").innerHTML = valNum - 273.15;
            }
        }
    </script>
</body>

1 个答案:

答案 0 :(得分:2)

尝试一下

document.getElementById("mytext").value = "My value";

相关问题