我从输入标签中获取输入,但无论我在输入框中写什么,它都会被识别为字符串值,因此我无法使用条件语句。
第二个问题是,如果我在第一个输入框中输入“ddd”,在第二个输入框中输入“111”,然后按下按钮,控制台会显示NaN。我想要弹出警告而不是这个结果。我该如何纠正这些问题?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
isNaN()
函数进行NaN检查。 - Alex K