我使用以下代码:
<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){alert("The first value more than the second value");}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick=asd()>
<br>
<textarea id="txt2"></textarea>
</body>
</html>
但代码工作不正确。
我正在写第一篇文章,5
我写了scnd textarea,40
并且警报有效。我不明白。我搜索并找到解决方案。
if( parseInt(b,10)) > (parseInt(c,10)) )
为什么第一次失败?
答案 0 :(得分:1)
您在方法
周围缺少引号<html>
<head>
<script type="text/javascript">
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( b > c ){
alert("The first value more than the second value");
}
}
</script>
</head>
<body>
<textarea id="txt"></textarea>
<input type="button" value="Click me" onclick="asd()">
<br>
<textarea id="txt2"></textarea>
</body>
</html>
答案 1 :(得分:0)
您的代码无法正常工作,因为您正在存储字符串。这就是为什么你无法正确比较它们。在比较它们或执行算术运算之前,需要将它们转换为整数数据类型。
function asd(){
var b = document.getElementById("txt").value;
var c = document.getElementById("txt2").value;
if( parseInt(b) > parseInt(c) ){alert("The first value more than the second value");}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
答案 2 :(得分:0)
第一次失败,因为数字被解析为字符串。
var b = document.getElementById("txt").value; //b = "5"
var c = document.getElementById("txt2").value; // c = "40"
if( b > c ){ // "5" > "40" is false because the browser will not understand this.
alert("The first value more than the second value");
}
如果使用parseInt,字符串将被解析为整数。
所以:
var b = document.getElementById("txt").value; //b = "5"
var d = parseInt(b); // d = 5
'大于/小于'符号仅适用于整数(和浮点数等),但不适用于字符串。这就是if语句返回false的原因。