1 回答
TA贡献1860条经验 获得超8个赞
问题是这一行:
const cTemp = parseFloat(celciusInput.value) || "";
该||操作符返回它的第一个操作数,如果它是truthy,否则返回第二opererand。如果用户输入0,则parseFloat()返回0,这是 falsey,因此cTemp设置为""而不是0。
您应该检查是否parseFloat()返回有效数字,而不是它是否为真。
let cTemp = parseFloat(celcisuInput.value);
…
if (isNaN(cTemp)) {
fahrenheitInput.value = "";
kelvinInput.value = "";
} else {
fahrenheitInput.value = Math.round(fTemp);
kelvinInput.value = Math.round(kTemp);
}
示例片段:
const celciusInput = document.querySelector("#celcius > input");
const fahrenheitInput = document.querySelector("#fahrenheit > input");
const kelvinInput = document.querySelector("#kelvin > input");
function celciusConverter() {
const cTemp = parseFloat(celciusInput.value);
const fTemp = cTemp * (9 / 5) + 32;
const kTemp = cTemp + 273.15;
if (isNaN(cTemp)) {
fahrenheitInput.value = "";
kelvinInput.value = "";
} else {
fahrenheitInput.value = Math.round(fTemp);
kelvinInput.value = Math.round(kTemp);
}
}
celciusInput.oninput = celciusConverter;
<div id="celcius">celcius: <input></div>
<div id="fahrenheit">fahrenheit: <input></div>
<div id="kelvin">kelvin: <input></div>
添加回答
举报