我从输入标签获得输入,但无论我在输入中写什么,它都识别为字符串值,因此我无法使用我的条件.
第二个问题,如果我输入"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!");
}
}Run Code Online (Sandbox Code Playgroud)
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>Run Code Online (Sandbox Code Playgroud)
输入字段的值始终为字符串.尝试使用isNaN()以确定是否正确解析了小数:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}Run Code Online (Sandbox Code Playgroud)
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>Run Code Online (Sandbox Code Playgroud)
或者,如果要消除所有错误输入(1e将无效),请尝试+在字符串值之前使用符号将其转换为数字.如果无法转换字符串,它将返回NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}Run Code Online (Sandbox Code Playgroud)
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>Run Code Online (Sandbox Code Playgroud)