【发布时间】:2019-01-03 17:37:34
【问题描述】:
我正在使用 typeof 命令来确保这个温度(摄氏度到华氏度)计算器的 2 个输入字段中只有一个填充了数据,并且它必须是一个数字。如果输入不是有效数字或两个字段均已填充,则应用程序将抛出错误消息。
问题:没有任何东西满足这个条件——errorMessage 总是显示出来,即使我输入了一个有效的数字。
typeof 是解决这个问题的正确方法吗?如果是,为什么这段代码不起作用?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
非常感谢!
【问题讨论】:
-
DOM 元素不是数字。你可以有一个
<input type="number">,其中 type 属性是数字,但元素的 typeof 不是。
标签: javascript forms validation if-statement typeof