我有两个输入字段,想用小于运算符比较它们。如果我在一个字段中插入小于10的值,而在其他字段中插入大于10的值,并且在它们之间使用较少的运算符,则它不会显示正确的答案
function myFunction() {
var x = document.getElementById("myInput").value;
var y = document.getElementById("h1").value;
alert(x);
if(y > x)
alert("good");
else
alert("ok");
}Run Code Online (Sandbox Code Playgroud)
<input type="number" id="myInput" onchange="myFunction()"/>
<input type="number" id="h1"/>Run Code Online (Sandbox Code Playgroud)
在typeof两者的input type='number'是字符串。因此,在进行比较之前,请先更改数字。您可以使用parseInt或使用一元运算符
function myFunction() {
var x = document.getElementById("myInput").value;
var y = document.getElementById("h1").value;
console.log(typeof(x), typeof(y))
if (parseInt(y, 10) > parseInt(x, 10))
alert("good");
else
alert("ok");
}Run Code Online (Sandbox Code Playgroud)
<input type="number" id="myInput" onchange="myFunction()" />
<input type="number" id="h1" />Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |