作为一名新的正在进行中的研究开发人员在这里发布的第一篇文章。:(
在Scrimba上,我的任务是创建一个从F到C的简单温度转换器。
我理解他们的解决方案,但似乎不明白为什么我的一直以NaN的形式返回。我知道这不是一个数字,但我认为我使用了parseInt((。
非常感谢您的帮助!
他们的工作解决方案
document.getElementById("btn").addEventListener("click", function() {
let fahrenheitTemp = document.getElementById("temperature").value;
fahrenheitTemp = parseInt(fahrenheitTemp);
document.getElementById("result").textContent = (( fahrenheitTemp - 32 ) * 5/9).toFixed(2);
})
我的解决方案问题
const convertBtn = document.querySelector(`#btn`);
let fahrenheitTemp = document.querySelector(`#temperature`).value;
const result = document.querySelector(`#result`);
function tempConversion() {
fahrenheitTemp = parseInt(fahrenheitTemp);
result.textContent = ((fahrenheitTemp - 32) * 5/9).toFixed(2);
}
convertBtn.addEventListener(`click`, tempConversion);
我认为这可能对你有用
function FernhtToCelcs() {
let feren = $("#temp")[0].value;
let celcs = (( feren - 32 ) * 5/9).toFixed(2);
document.getElementById("tempincec").innerHTML = celcs + ' C';
}
input {
width: 50px;
height: 20px;
}
button {
background: #0095ff;
border: none;
border-radius: 3px;
padding: 7px;
color: white;
cursor: pointer;
}
#tempincec {
font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="temp">Temprature in fahrenheit : </label>
<input type="number" id="temp" name="temp">
<button onclick="FernhtToCelcs()">Convert</button>
</div>
<p>Temprature in celcius : <span id="tempincec"></span></p>
我认为你的问题在于这一行:
fahrenheitTemp = document.getElementById("temperature").value;
您正在将一个值转化为";常规的";变量
它没有"活的";连接到HTML元素
请尝试:
fahrenheitTemp = document.getElementById("temperature");
并且,在您的函数中,而不是:
fahrenheitTemp = parseInt(fahrenheitTemp);
用途:
fahrenheitTemp = parseInt(fahrenheitTemp.value);