尝试创建用于转换华氏度和摄氏度的按钮

Trying to create buttons for converting Fahrenheit and Celsius

var typeTemp = document.getElementById("demo3");

document.getElementById("f").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // allows the number to be functional
    
    document.getElementById("Fanswer").innerHTML = (1.8 * tValue) + 32;
});

document.getElementById("c").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // allows the number to be functional
    
    document.getElementById("Canswer").innerHTML = 1.8 * (tValue - 32);
});
   <input type="number" id="demo3" class="ex" min=0><br>
        <button id="f">Fahrenheit</button>
        <div id="Fanswer"></div>
        <button id="c">Celsius</button>
        <div id="Canswer"></div>

您好,我正在尝试使华氏温度和摄氏温度按钮起作用,并使答案显示在 div 中。我检查时没有错误,但我确实得到了两个函数的 "NaN" 。我不确定为什么要这样做:( 谢谢。

typeTemp 是对 DOM 元素的引用,但您将其用作字符串(元素的值)。你想使用它的 .value 属性,见 *** 评论:

var typeTemp = document.getElementById("demo3");

document.getElementById("f").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // ***
    
    document.getElementById("Fanswer").innerHTML = (1.8 * tValue) + 32;
});

document.getElementById("c").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // ***
    
    document.getElementById("Canswer").innerHTML = 1.8 * (tValue - 32);
});
<input type="number" id="demo3" class="ex"><br>
        <button id="f">Fahrenheit</button>
        <div id="Fanswer"></div>
        <button id="c">Celsius</button>
        <div id="Canswer"></div>

你得到 NaN 的原因有点复杂,但是:

  • parseFloat 将尝试将您提供的内容强制转换为字符串
  • 你给了它一个 DOM 元素
  • 当您将 DOM 元素强制转换为字符串时,通常您会得到类似 "[object HTMLInputElement]"
  • 的字符串
  • parseFloat returns NaN 如果它甚至不能将你给它的字符串的第一部分转换为数字,在 "[object HTMLInputElement]"

问题是您使用 typeTemp 作为值,而实际上它是 DOM 节点,您应该像这样编辑它:

var typeTemp = document.getElementById("demo3");

document.getElementById("f").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // allows the number to be functional

    document.getElementById("Fanswer").innerHTML = (1.8 * tValue) + 32;
});

document.getElementById("c").addEventListener("click", function(){
    var tValue = parseFloat(typeTemp.value); // allows the number to be functional

    document.getElementById("Canswer").innerHTML = 1.8 * (tValue - 32);
});